zdog
Version:
Round, flat, designer-friendly pseudo-3D engine
81 lines (64 loc) • 1.87 kB
JavaScript
/**
* SvgRenderer
*/
( function( root, factory ) {
// module definition
if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
root.Zdog.SvgRenderer = factory();
}
}( this, function factory() {
var SvgRenderer = { isSvg: true };
// round path coordinates to 3 decimals
var round = SvgRenderer.round = function( num ) {
return Math.round( num * 1000 ) / 1000;
};
function getPointString( point ) {
return round( point.x ) + ',' + round( point.y ) + ' ';
}
SvgRenderer.begin = function() {};
SvgRenderer.move = function( svg, elem, point ) {
return 'M' + getPointString( point );
};
SvgRenderer.line = function( svg, elem, point ) {
return 'L' + getPointString( point );
};
SvgRenderer.bezier = function( svg, elem, cp0, cp1, end ) {
return 'C' + getPointString( cp0 ) + getPointString( cp1 ) +
getPointString( end );
};
SvgRenderer.closePath = function( /* elem */) {
return 'Z';
};
SvgRenderer.setPath = function( svg, elem, pathValue ) {
elem.setAttribute( 'd', pathValue );
};
SvgRenderer.renderPath = function( svg, elem, pathCommands, isClosed ) {
var pathValue = '';
pathCommands.forEach( function( command ) {
pathValue += command.render( svg, elem, SvgRenderer );
} );
if ( isClosed ) {
pathValue += this.closePath( svg, elem );
}
this.setPath( svg, elem, pathValue );
};
SvgRenderer.stroke = function( svg, elem, isStroke, color, lineWidth ) {
if ( !isStroke ) {
return;
}
elem.setAttribute( 'stroke', color );
elem.setAttribute( 'stroke-width', lineWidth );
};
SvgRenderer.fill = function( svg, elem, isFill, color ) {
var fillColor = isFill ? color : 'none';
elem.setAttribute( 'fill', fillColor );
};
SvgRenderer.end = function( svg, elem ) {
svg.appendChild( elem );
};
return SvgRenderer;
} ) );