JavaScript Canvas - 矩形绕圆旋转

Ama*_*may 2 javascript canvas

我正在尝试制作一个矩形,使其绕圆旋转并绕其自身旋转。我精彩的图画将表达我的意思:)

在此输入图像描述

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

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

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

mar*_*rkE 5

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

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