Converting SVG to JavaScript

SVG conversions can be done using JavaScript using the appropriate setAttribute("transform", "translate(x,y)") attributes, but should also be possible with pure JavaScript.

 elem.transform.baseVal.getItem(0).setTranslate(x, y); elem.transform.baseVal.getItem(0).setRotate(x, y); 

These two should work for translation and rotation, but what about skew, scale, and matrix? elem.transform.baseVal.getItem(0).setMatrix() exists, but as far as I can tell, it does not exclude any parameters and SVGCreateMatrix() does not accept any parameters. How should I do this, and as a bonus question: what does getItem(0) actually do?

+8
javascript svg transform translation transformation
source share
1 answer

Each <svg> element has a createSVGMatrix dom method.

 var matrix = svgElement.createSVGMatrix(); 

This is the identity matrix.

You can manipulate this ...

 matrix = matrix.translate(10, 10); 

or directly ...

 matrix.a = 3; 

and then use it

 elem.transform.baseVal.getItem(0).setMatrix(matrix); 

getItem (0) gets the first element in the transform attribute, for example.

 transform="translate(1, 1) scale(2)" 

getItem(0) gets the translate(1, 1) matrix, and getItem(1) gets the scale(2) matrix

If you did not specify an element conversion, then getItem(0) will throw. You can check how many elements numberOfItems uses and / or add an initial element using createSVGTransformFromMatrix to turn your matrix into a transform and appendItem to add a transform.

+19
source share

All Articles