JavaScript 中的 SVG 转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16810948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SVG Transformations in JavaScript
提问by sluijs
SVG Transformations can be done through JavaScript by settings their corresponding attributes setAttribute("transform", "translate(x,y)")
but should also be possible through pureJavaScript.
SVG 转换可以通过 JavaScript 通过设置其相应的属性来完成,setAttribute("transform", "translate(x,y)")
但也应该可以通过纯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?
这两个应该适用于平移和旋转,但是倾斜、缩放和矩阵呢?elem.transform.baseVal.getItem(0).setMatrix()
存在,但据我所知,它不排除任何参数,SVGCreateMatrix()
也不接受任何参数。我该怎么做,作为一个额外的问题:getItem(0)
实际上是做什么的?
回答by Robert Longson
Each <svg>
element has a createSVGMatrixdom method.
每个<svg>
元素都有一个createSVGMatrixdom 方法。
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.
getItem(0)获取转换属性中的第一个元素,例如
transform="translate(1, 1) scale(2)"
getItem(0)
gets the translate(1, 1)
matrix and getItem(1)
gets the scale(2)
matrix
getItem(0)
得到translate(1, 1)
矩阵并getItem(1)
得到scale(2)
矩阵
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.
如果您尚未对元素设置转换,getItem(0)
则将抛出。您可以检查有多少项正在使用numberOfItems
和/或添加一个初始项,createSVGTransformFromMatrix
用于将矩阵转换为变换并appendItem
附加变换。