如何使对象跟随路径动画

时间:2012-11-18 01:15:04

标签: javascript raphael

我已设置jsFiddle来说明我的问题。

我希望动画期间红色圆圈留在路径上。这样做有“简单”的方法吗?

var r = Raphael(0, 0, "100%", "100%");

(function () {
    var el = r.path("M0 100L200 100").attr({fill: "none"}),
        elattrs = [{path: "M0 100L200 100"}, {path: "M0 100S100 150 200 100"}],
        now = 1;
    var set = r.set();
    set.push(
        el,
        r.circle(100, 100, 5).attr({fill: 'red'}),
        r.circle(50, 100, 5).attr({fill: 'red'}),
        r.circle(150, 100, 5).attr({fill: 'red'})
    );

    r.circle(40, 40, 20).attr({fill: 'blue'}).click(function () {
        el.stop().animate(elattrs[+(now = !now)], 1000, 'elastic');
    });
})();

1 个答案:

答案 0 :(得分:3)

有一个很好的方法Element.getPointAtLength可以用于此目的。

forked and updated your code让圈元素按照您的意愿跟随动画路径。 Stackoverflow强迫我将代码粘贴到这里,所以这里是:

var r = Raphael(0, 0, "100%", "100%");

(function () {
    var paths = ["M0 100 L200 100",
                 "M0 100 S100 150 200 100"];
    var line = r.path(paths[0]).attr({fill: "none"}),
        elattrs = [{path: paths[0]}, {path: paths[1]}],
        now = 1;
    var guide = r.path(paths[1]).attr({stroke : "none"});
    var c1 = r.circle(50, 100, 5).attr({fill: 'red'}),
        c2 = r.circle(100, 100, 5).attr({fill: 'red'}),
        c3 = r.circle(150, 100, 5).attr({fill: 'red'});

    r.circle(40, 40, 20).attr({fill: 'blue'}).click(function () {
        now = now ? 0 : 1;
        line.stop().animate(elattrs[now], 1000, 'elastic');
        c1.stop().animate({cy : (now ? guide.getPointAtLength(50).y  : 100)}, 1000, 'elastic');
        c2.stop().animate({cy : (now ? guide.getPointAtLength(100).y : 100)}, 1000, 'elastic');
        c3.stop().animate({cy : (now ? guide.getPointAtLength(150).y : 100)}, 1000, 'elastic');
    });
})();

PS。查看更多示例over here

相关问题