Reputation: 4433
I created a gear like object using canvas, now I want it to rotate.With that said, I tried to implement this, but what is happening is that the entire canvas is being rotated, which is not what I want. Here is my code:
var ctx = document.getElementById("canvas").getContext("2d"),
i = 0;
function init(){
drawGear();
setInterval(drawGear,1000);
}
var i = 0;
function drawGear(){
ctx.clearRect(0,0,200,200);
ctx.beginPath();
ctx.fillStyle = "#000";
ctx.translate(100,100);
ctx.arc(0,0,20,0,Math.PI*2);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "#FFF";
ctx.arc(0,0,10,0,Math.PI*2);
ctx.fill();
ctx.closePath();
for(var i=0; i<9; i++){
drawTooth(-8,-18);
ctx.rotate(45*Math.PI/180);
}
ctx.rotate(i*Math.PI/180);
i++;
}
function drawTooth(startX,startY){
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(startX+5,startY-10);
ctx.lineTo(startX+10,startY-10);
ctx.lineTo(startX+15,startY);
ctx.closePath();
ctx.fill();
}
init();
Upvotes: 1
Views: 113
Reputation: 63812
Rotation always occurs on the origin of the context.
You need to translate the context (to change the origin point to the center of what you want to rotate), rotate the object, and then translate back.
So you need to do something like:
function drawGear(){
...
ctx.translate(100,100);
...
for(var i=0; i<8; i++){
drawTooth(-8,-18);
ctx.rotate(45*Math.PI/180);
}
ctx.rotate(i*Math.PI/180);
ctx.translate(-100,-100);
i++;
}
See here: http://jsfiddle.net/MsjyN/1/
By the way you had one more gear tooth being drawn than necessary, which was apparent when I changed the gear teeth to semi-transparent (just for testing purposes)
Upvotes: 2