使用Raphael.js动态观察动画?

2022-05-24 00:00:00 javascript raphael

Raphael.js的新手,我正在寻找一个关于如何做一些事情的解释,比如在轨道上围绕太阳移动行星。我被困在试图创建一条路径并使圆围绕它的运动动画化。

感谢您给我们指明正确的方向!


解决方案

我的朋友@Kevin Nielsen是对的,您会想要"getPointAtLength"。有一个很好的小Raphael函数here,它添加了一个.AnimateAlong()函数,尽管它需要稍作修改才能处理圆形对象。我把它脱掉了,只为你提供必需品。

假设您认识1609年后的天文学,you'll want elliptical orbits。(尽管在现实中,短半径和长半径的差别很小,这就是为什么哥白尼有点偏离了目标。)但是您不能使用.lipse()函数,因为您需要将椭圆作为路径才能沿其设置动画。请参阅elliptical arc的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);

现在您想要在椭圆的一个焦点处绘制地球,并沿路径绘制月球。我们将从perigee开始。

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

下面是修改后的"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);
    });    
};

这就是:

moon.animateAlong(orbit, 2000);

jsFiddle

相关文章