Flat, round, designer-friendly pseudo-3D engine for canvas & SVG
1/**
2 * SvgRenderer
3 */
4
5( function( root, factory ) {
6 // module definition
7 if ( typeof module == 'object' && module.exports ) {
8 // CommonJS
9 module.exports = factory();
10 } else {
11 // browser global
12 root.Zdog.SvgRenderer = factory();
13 }
14}( this, function factory() {
15
16var SvgRenderer = { isSvg: true };
17
18// round path coordinates to 3 decimals
19var round = SvgRenderer.round = function( num ) {
20 return Math.round( num * 1000 ) / 1000;
21};
22
23function getPointString( point ) {
24 return round( point.x ) + ',' + round( point.y ) + ' ';
25}
26
27SvgRenderer.begin = function() {};
28
29SvgRenderer.move = function( svg, elem, point ) {
30 return 'M' + getPointString( point );
31};
32
33SvgRenderer.line = function( svg, elem, point ) {
34 return 'L' + getPointString( point );
35};
36
37SvgRenderer.bezier = function( svg, elem, cp0, cp1, end ) {
38 return 'C' + getPointString( cp0 ) + getPointString( cp1 ) +
39 getPointString( end );
40};
41
42SvgRenderer.closePath = function( /* elem */) {
43 return 'Z';
44};
45
46SvgRenderer.setPath = function( svg, elem, pathValue ) {
47 elem.setAttribute( 'd', pathValue );
48};
49
50SvgRenderer.renderPath = function( svg, elem, pathCommands, isClosed ) {
51 var pathValue = '';
52 pathCommands.forEach( function( command ) {
53 pathValue += command.render( svg, elem, SvgRenderer );
54 } );
55 if ( isClosed ) {
56 pathValue += this.closePath( svg, elem );
57 }
58 this.setPath( svg, elem, pathValue );
59};
60
61SvgRenderer.stroke = function( svg, elem, isStroke, color, lineWidth ) {
62 if ( !isStroke ) {
63 return;
64 }
65 if (color && color.getSvgFill) {
66 color = color.getSvgFill(svg);
67 }
68 elem.setAttribute( 'stroke', color );
69 elem.setAttribute( 'stroke-width', lineWidth );
70};
71
72SvgRenderer.fill = function( svg, elem, isFill, color ) {
73 var fillColor = isFill ? color : 'none';
74 if (fillColor && fillColor.getSvgFill) {
75 fillColor = fillColor.getSvgFill(svg);
76 }
77 elem.setAttribute( 'fill', fillColor );
78};
79
80SvgRenderer.end = function( svg, elem ) {
81 svg.appendChild( elem );
82};
83
84return SvgRenderer;
85
86} ) );