Search code examples
htmlcanvasphysicsgame-physics

How can I animate an object in orbit using HTML5 Canvas?


Lets say I've already drawn all my objects, a sun in the middle and a couple of circles for planets. Can someone enlighten me as to how I make these objects move around in a circular fashion? I don't need any gravity etc but I suppose that could be a sweet bonus!

Thanks :)


Solution

  • Here's a crude solution:

    var canvas = document.getElementById('scene');
    var ctx = canvas.getContext('2d');
    var w = canvas.width;
    var h = canvas.height;
    
    var circle = function(color, r) {
        ctx.fillStyle = color;
    
        ctx.beginPath();
        ctx.arc(0, 0, r, 0, 2 * Math.PI, true);
        ctx.closePath();
    
        ctx.fill();
    }
    
    var i = 0;
    var redraw = function() {
        ctx.save();
    
        // paint bg
        ctx.fillStyle = 'black';
        ctx.fillRect(0, 0, w, h);
    
        // set origin to center
        ctx.translate(w / 2, h / 2);
    
        // draw sun
        circle('yellow', 20);
    
        // rotate + move along x
        ctx.rotate(i / 100);
        ctx.translate(100, 0);
    
        // draw planet
        circle('green', 10);
    
        ctx.restore();
    
        i++;
    
        window.requestAnimationFrame(redraw);
    };
    
    window.requestAnimationFrame(redraw);
    

    You can find a demo here. Extend as needed. :)