JavaScript Canvas - Rectangle rotates around circle
Amma
I'm trying to make a rectangle to rotate around a circle and rotate around itself. My wonderful drawing will show what I mean :)
I made a rotated rectangle around the circle, but I cannot rotate the rectangle around it. 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(); });
Card
You can use the canvas transform to rotate the rectangle around the center point:
Demo : 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;
}