JavaScript中的SVG转换 [英] SVG Transformations in JavaScript

查看:145
本文介绍了JavaScript中的SVG转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SVG转换可以通过JavaScript设置相应的属性setAttribute("transform", "translate(x,y)")来完成,但也可以通过 pure JavaScript来实现.

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);

这两个应该可以平移和旋转,但是倾斜,缩放和矩阵又如何呢? elem.transform.baseVal.getItem(0).setMatrix()存在,但据我所知,它不排除任何参数,并且SVGCreateMatrix()也不接受任何参数.我应该怎么做,还有一个额外的问题:getItem(0)实际上是做什么的?

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>元素都有一个 createSVGMatrix dom方法.

Each <svg> element has a createSVGMatrix dom method.

var matrix = svgElement.createSVGMatrix();

这是身份矩阵.

然后您可以进行操作 ...

matrix = matrix.translate(10, 10);

或直接...

matrix.a = 3;

然后使用它

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

getItem(0)获取转换属性中的第一个元素,例如

getItem(0) gets the first element in a transform attribute e.g.

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

getItem(0)获取translate(1, 1)矩阵,getItem(1)获取scale(2)矩阵

如果尚未在元素上设置转换,则将抛出getItem(0).您可以使用numberOfItems检查有多少项,和/或使用createSVGTransformFromMatrix添加初始项以将矩阵转换为变换,并使用appendItem追加变换.

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.

这篇关于JavaScript中的SVG转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆