如何在Raphaël中设置旋转和变换的动画

时间:2011-06-02 13:34:01

标签: javascript raphael

我正在尝试做一些我认为相当简单的事情。我有一个逐步移动的对象,即我每隔100毫秒收到一条消息,告诉我“你的对象向右移动x像素,向下移动y像素”。下面的代码模拟了通过在圆上移动该对象,但请注意事先不知道对象将在下一步中前进的位置。

无论如何,这很简单。但现在我想告诉对象,它实际上是一组子对象,它正在被旋转。

不幸的是,我无法让Raphaël做我想做的事。我相信原因是虽然我可以独立地为平移和旋转设置动画,但我必须在启动时设置旋转的中心。显然,当物体移动时,旋转的中心会发生变化。

以下是我正在使用的代码,您可以查看实时演示here。如您所见,方块按预期旋转,但箭头旋转不正确。

// c&p this into http://raphaeljs.com/playground.html

var WORLD_SIZE = 400,
    rect = paper.rect(WORLD_SIZE / 2 - 20, 0, 40, 40, 5).attr({ fill: 'red' }),
    pointer = paper.path("M 200 20 L 200 50"),
    debug = paper.text(25, 10, ""),
    obj = paper.set();

obj.push(rect, pointer);

var t = 0,
    step = 0.05;

setInterval(function () {
    var deg = Math.round(Raphael.deg(t));

    t += step;

    debug.attr({ text: deg + '°' });

    var dx = ((WORLD_SIZE - 40) / 2) * (Math.sin(t - step) - Math.sin(t)),
        dy = ((WORLD_SIZE - 40) / 2) * (Math.cos(t - step) - Math.cos(t));

    obj.animate({
        translation: dx + ' ' + dy,
        rotation: -deg
    }, 100);
}, 100);

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

如果你想进行翻译和轮换,那么raphael obj应该是那样的

 obj.animate({
     transform: "t" + [dx , dy] + "r" + (-deg)
 }, 100);

答案 1 :(得分:0)

查看http://raphaeljs.com/animation.html

从右上角看第二个动画。

希望这有帮助!

以下是代码:

(function () {
    var path1 = "M170,90c0-20 40,20 40,0c0-20 -40,20 -40,0z",
        path2 = "M270,90c0-20 40,20 40,0c0-20 -40,20 -40,0z";
    var t = r.path(path1).attr(dashed);
    r.path(path2).attr({fill: "none", stroke: "#666", "stroke-dasharray": "- ", rotation: 90});
    var el = r.path(path1).attr({fill: "none", stroke: "#fff", "stroke-width": 2}),
        elattrs = [{translation: "100 0", rotation: 90}, {translation: "-100 0", rotation: 0}],
        now = 0;
    r.arrow(240, 90).node.onclick = function () {
        el.animate(elattrs[now++], 1000);
        if (now == 2) {
            now = 0;
        }
};                })(); 
相关问题