如何使用snap.svg获取SVG对象的旋转值?

4

我正在使用snap.svg,想要动态地旋转一个对象。就像这样:

function rotateObject()
{
    myObject.rotation += value;
}

问题是我不知道如何访问我的显示对象的旋转值(或者它们是否存在!)。所以,假设有一个简单的对象,比如这样声明一个圆形:
snap = Snap(800,600);   
circle = snap.circle(400,300,50);

我知道可以这样访问x和y的值:

circle.attr("cx");
circle.attr("cy");

我需要帮忙的是:

  1. 是否有某种旋转属性可以用来旋转这个对象?
  2. 如果没有,如何使用snap.svg旋转对象?
2个回答

6

使用Snap.Matrix()更好地旋转对象。

Ian建议的方法,在我使用Chrome版本<36.0时完美地运行。当我更新到Chrome 36.0.1985.125时,发现了一些文本旋转上的错误。

因此,解决方案是使用以下内容:

var matrix = new Snap.Matrix();
matrix.rotate(-90, x, y);    
Paper.text(x, y, 'Text').attr({
                    fontWeight: 'bold',
                    fill: '#434343',
                    transform: matrix
                });

替代

Paper.text(x, y, 'Text').attr({
                    fontWeight: 'bold',
                    fill: '#434343',
                    transform: 'r-90'
                });

也许对某些人会有帮助。

5
理想情况下,您将自己控制旋转(而不是从属性中找出),这可能有些麻烦。根据您的需求,动画可能会更容易。以下是一个示例,展示了使用矩形进行基本动画效果(因为圆形旋转只需要绕中心旋转)...
s = Snap(400, 620);

var myRect = s.rect(100, 100, 100, 200).attr({
    fill : 'white',
    stroke : 'black'
});
var myRotate = 45;

// if you wanted to rotate manually using your own adjust variable then this
// myRect.transform("r" + myRotate);
// but simpler in most cases to use the animate method


myRect.animate( { transform: "r" + myRotate + ",150,200" }, 1000 ); //rotate around centre of 150,200

http://jsfiddle.net/XG7ks/6/上试验。

实际上最好先对SVG的变换(平移、旋转、缩放)有一个基础的了解,这样才能更好地理解它。你可以用myRect.attr('transform')来“查看”结果变换,但起初最好不要管它。


好的,这让我很有道路可循。非常感谢! - Paul Mignard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接