Why does Raphael's framerate slow down on this code?

后端 未结 1 1733
予麋鹿
予麋鹿 2021-01-03 13:28

So I\'m just doing a basic orbit simulator using Raphael JS, where I draw one circle as the \"star\" and another circle as the \"planet\". It seems to be working just fine,

相关标签:
1条回答
  • 2021-01-03 14:10

    The problem is with the call back to calculateOrbit in your planet.animate() call. Its not being handled by raphael correctly and is causing a memory leak or an execution slow down. if you remove it and replace the line

    calculateOrbit()
    

    with

    setInterval(calculateOrbit, 150);
    

    it should run smoothly.

    full code:

    $(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);
    });
    
    0 讨论(0)
提交回复
热议问题