JavaScript Canvas - 矩形旋转圆圈

时间:2014-03-24 20:00:34

标签: javascript canvas

我正在尝试制作一个围绕圆圈旋转的矩形并自行旋转。我精彩的绘画将展示我的意思:)

enter image description here

我在圆圈周围做了一个旋转的矩形,但是我无法围绕它自己旋转矩形。有人能帮我吗?我的代码:

var game = {

        canvas: document.getElementById('mycanvas'),

        ctx: document.getElementById('mycanvas').getContext('2d'), 

        char: {
            x: 100,
            y: 100,
            w: 50,
            h: 50,
            inc: 0
        },

        init: function() {
            game.drawAll();

        },

        Player: {
            move: function() {

                game.char.inc += 0.05;

                var 
                    x = game.char.inc, 
                    y = game.char.inc;

                    game.char.x = 100 * (Math.cos(x));
                    game.char.y = 100 * (Math.sin(y));

            }

        },

        drawAll: function() {
            game.ctx.clearRect(0,0,800,600);
            game.ctx.save();
            game.ctx.translate(400, 300);
            game.ctx.rotate(Math.cos(game.char.inc));
            game.ctx.fillRect(game.char.x, game.char.y, game.char.w, game.char.h);
            game.ctx.translate(-400, -300);
            window.requestAnimationFrame(game.drawAll);
            game.Player.move();
        }
}
$(function() { game.init(); });

http://jsfiddle.net/mQpSu/2/

1 个答案:

答案 0 :(得分:3)

您可以使用画布变换围绕中心点旋转矩形:

演示:http://jsfiddle.net/m1erickson/k6B2z/

function animate(){

    // request that the animation continues when this frame is done

    requestAnimationFrame(animate);

    // draw a circle for the rect to rotate around

    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.arc(cx,cy,10,0,Math.PI*2);
    ctx.closePath();
    ctx.fill();

    // save the untransformed context state

    ctx.save();

    // move the origin(0,0) of the canvas to cx,cy

    ctx.translate(cx,cy);

    // rotate the entire canvas around the new origin(cx,cy)

    ctx.rotate(rotation);

    // draw a rectangle
    // note: just draw it like it's in unrotated space
    // translate+rotate make this possible without needing lots of math!

    ctx.strokeRect(-rectWidth/2+20,-rectHeight/2,rectWidth,rectHeight);

    // restore the context to its untransformed state

    ctx.restore();

    rotation+=Math.PI/360;
}