使用raphael.js进行轨道动画?

boo*_*oom 1 javascript raphael

raphael.js的新手,我正在寻找关于如何在轨道上围绕太阳移动行星的解释.我试图创建一条路径,并围绕它围绕圆圈的运动制作动画.

感谢您指出正确的方向!

Chr*_*son 7

我的朋友@Kevin Nielsen是对的,你会想要"getPointAtLength".这里有一个很好的小拉斐尔函数,它添加了一个.animateAlong()函数,虽然它需要一些修改来处理圆形对象.我把它剥夺了你的必需品.

假设你认识1609年后的天文学,你会想要椭圆轨道.(虽然短半径和长半径的差异实际上很小,这就是为什么哥白尼有点偏离标记.)但是你不能使用.ellipse()函数,因为你需要椭圆作为路径为了沿着它动画.请参阅SVG规范中的椭圆弧,或者只是尝试一堆组合,直到它看起来正确,就像我做的那样:

var paper = Raphael("canvas", 500, 500);

var center = {x: 200, y: 100 };
var a = 100;
var b = 80;

//see http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
var ellipse = "M" + (center.x - a) + "," + center.y + " a " + a + "," + b + " 0 1,1 0,0.1";

var orbit = paper.path(ellipse);
Run Code Online (Sandbox Code Playgroud)

现在你想在椭圆的一个焦点和沿着路径的月亮上绘制地球.我们将在近地点开始.

var focus = Math.pow(a*a - b*b, 0.5);

var palebluedot = paper.circle(center.x - focus, center.y, 25)
    .attr({
        stroke: 0,
        fill: "blue"    
    });

var moon = paper.circle(center.x - a, center.y, 10)
.attr({
    stroke: 0,
    fill: "#CCC"
});
Run Code Online (Sandbox Code Playgroud)

这是您修改后的"animateAlong"功能:

//Adapted from https://github.com/brianblakely/raphael-animate-along/blob/master/raphael-animate-along.js
Raphael.el.animateAlong = function(path, duration, easing, callback) {
    var element = this;
    element.path = path;
    element.pathLen = element.path.getTotalLength();    
    duration = (typeof duration === "undefined") ? 5000 : duration;
    easing = (typeof easing === "undefined") ? "linear" : duration;

    //create an "along" function to take a variable from zero to 1 and return coordinates. Note we're using cx and cy specifically for a circle    
paper.customAttributes.along = function(v) {
        var point = this.path.getPointAtLength(v * this.pathLen),
            attrs = {
                cx: point.x,
                cy: point.y 
            };
        this.rotateWith && (attrs.transform = 'r'+point.alpha);
        return attrs;
    };    

    element.attr({along: 0 }).animate({along: 1}, duration, easing, function() {
        callback && callback.call(element);
    });    
};
Run Code Online (Sandbox Code Playgroud)

这是:

moon.animateAlong(orbit, 2000);
Run Code Online (Sandbox Code Playgroud)

的jsfiddle