简体   繁体   English

JavaScript Canvas - 矩形旋转圆圈

[英]JavaScript Canvas - rectangle spin around circle

I'm trying to make a rectangle to spin around a circle and to spin around itself. 我正在尝试制作一个矩形旋转圆圈并绕自身旋转。 My brilliant drawing will show what i mean :) 我的精彩绘画将展示我的意思:)

在此输入图像描述

I made a spinning rectangle around the circle but I can't make to spin rectangle around itself. 我在圆圈周围做了一个旋转的矩形,但我无法围绕它自己旋转矩形。 Can someone help me? 有人能帮我吗? My code: 我的代码:

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/ http://jsfiddle.net/mQpSu/2/

You can use canvas transforms to rotate your rectangle around a centerpoint: 您可以使用画布变换围绕中心点旋转矩形:

A demo: http://jsfiddle.net/m1erickson/k6B2z/ 演示: 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM