最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

SVG Transformations in JavaScript - Stack Overflow

programmeradmin5浏览0评论

SVG Transformations can be done through JavaScript by settings their corresponding attributes setAttribute("transform", "translate(x,y)") but should also be possible through 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 how about skewing, scaling and matrix? elem.transform.baseVal.getItem(0).setMatrix() exists, but as far as I can tell, it doesn't excepts any params and SVGCreateMatrix() does not accept any params either. How am I supposed to do this, and as a bonus question: what does getItem(0) actually do?

SVG Transformations can be done through JavaScript by settings their corresponding attributes setAttribute("transform", "translate(x,y)") but should also be possible through 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 how about skewing, scaling and matrix? elem.transform.baseVal.getItem(0).setMatrix() exists, but as far as I can tell, it doesn't excepts any params and SVGCreateMatrix() does not accept any params either. How am I supposed to do this, and as a bonus question: what does getItem(0) actually do?

Share Improve this question edited Apr 16, 2020 at 7:24 sluijs asked May 29, 2013 at 10:02 sluijssluijs 4,2274 gold badges32 silver badges37 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 30

Each <svg> element has a createSVGMatrix dom method.

var matrix = svgElement.createSVGMatrix();

This is the identity matrix.

You can then 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 a transform attribute e.g.

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

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

If you haven't set a transform on an element then getItem(0) will throw. You can check how many items there are using numberOfItems and/or add an initial item using createSVGTransformFromMatrix to turn your matrix into a transform and appendItem to append the transform.

发布评论

评论列表(0)

  1. 暂无评论