如何使用HTML5 Canvas为轨道中的对象设置动画?

Hen*_*ryz 1 html5 physics canvas game-physics

让我们说我已经绘制了所有的物体,中间的太阳和行星的几个圆圈.有人可以告诉我如何让这些物体以循环方式移动吗?我不需要任何重力等但我想这可能是一个甜蜜的奖金!

谢谢 :)

Juh*_*nen 5

这是一个粗略的解决方案:

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);
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到一个演示.根据需要扩展.:)