为什么Raphael的帧速率在这段代码上变慢了?

时间:2010-04-28 22:40:46

标签: raphael

所以我只是使用Raphael JS做一个基本轨道模拟器,在那里我绘制一个圆作为“星”,另一个圆作为“行星”。它似乎工作得很好,随着模拟的继续,它的帧速率逐渐减慢,直到轨道运动不再出现流动。这是代码(注意:仅使用jQuery初始化页面):

$(function() {
    var paper = Raphael(document.getElementById('canvas'), 640, 480);
    var star = paper.circle(320, 240, 10);
    var planet = paper.circle(320, 150, 5);
    var starVelocity = [0,0];
    var planetVelocity = [20.42,0];
    var starMass = 3.08e22;
    var planetMass = 3.303e26;
    var gravConstant = 1.034e-18;
    function calculateOrbit() {
        var accx = 0;
        var accy = 0;
        accx = (gravConstant * starMass * ((star.attr('cx') - planet.attr('cx')))) / (Math.pow(circleDistance(), 3));
        accy = (gravConstant * starMass * ((star.attr('cy') - planet.attr('cy')))) / (Math.pow(circleDistance(), 3));
        planetVelocity[0] += accx;
        planetVelocity[1] += accy;
        planet.animate({cx: planet.attr('cx') + planetVelocity[0], cy: planet.attr('cy') + planetVelocity[1]}, 150, calculateOrbit);
        paper.circle(planet.attr('cx'), planet.attr('cy'), 1); // added to 'trace' orbit
    }
    function circleDistance() {
        return (Math.sqrt(Math.pow(star.attr('cx') - planet.attr('cx'), 2) + Math.pow(star.attr('cy') - planet.attr('cy'), 2)));
    }
    calculateOrbit();
});

无论如何,对我来说,该代码的任何部分都不会导致动画逐渐变慢,所以任何有助于解决问题的人都会受到赞赏!

1 个答案:

答案 0 :(得分:3)

问题在于你的planet.animate()调用中的calculateOrbit回调。它没有正确处理raphael并导致内存泄漏或执行速度变慢。如果你删除它并替换行

calculateOrbit()

setInterval(calculateOrbit, 150);

它应该顺利运行。

完整代码:

$(function() {
var paper = Raphael(document.getElementById('canvas'), 640, 480);
var star = paper.circle(320, 240, 10);
var planet = paper.circle(320, 150, 5);
var starVelocity = [0,0];
var planetVelocity = [20.42,0];
var starMass = 3.08e22;
var planetMass = 3.303e26;
var gravConstant = 1.034e-18;
function calculateOrbit() {
    var accx = 0;
    var accy = 0;
    accx = (gravConstant * starMass * ((star.attr('cx') - planet.attr('cx')))) / (Math.pow(circleDistance(), 3));
    accy = (gravConstant * starMass * ((star.attr('cy') - planet.attr('cy')))) / (Math.pow(circleDistance(), 3));
    planetVelocity[0] += accx;
    planetVelocity[1] += accy;
    planet.animate({cx: planet.attr('cx') + planetVelocity[0], cy: planet.attr('cy') + planetVelocity[1]}, 150);
    paper.circle(planet.attr('cx'), planet.attr('cy'), 1); // added to 'trace' orbit
}
function circleDistance() {
    return (Math.sqrt(Math.pow(star.attr('cx') - planet.attr('cx'), 2) + Math.pow(star.attr('cy') - planet.attr('cy'), 2)));
}
setInterval(calculateOrbit, 150);
});