I’m trying to animate a rotating repeat icon on a canvas but it’s not spinning around the center of the image. I’m not sure what to do to make it spin properly.
setInterval(draw, 30);
var degrees = 0.0;
function draw() {
var canvas = document.getElementById('tutorial');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 16, 16);
degrees += 0.10;
ctx.save();
ctx.translate(8,8);
ctx.rotate(degrees);
// Draw half open circle
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(8, 8, 6, 0, 1.75 * Math.PI);
ctx.stroke();
// Draw arrowhead
ctx.lineWidth = 2;
ctx.moveTo(13, 1);
ctx.lineTo(9, 5);
ctx.lineTo(13, 5);
ctx.lineTo(13, 1);
ctx.stroke();
ctx.restore();
}
}
Fiddle: http://jsfiddle.net/xTFkU/
You were rotating the canvas and translating, but drawing then performing your drawing functions as if the canvas wasn’t translated.
Basically what you need to do is translate the canvas to half of the width and height of the image you’re drawing. This will make 0,0 the center of the image. Then you subtract the offset from all of your coordinates.
What I did was add an offset value that is your width and height divided by 2. I then translated the canvas by that offset, and subtracted that offset from all of the coordinates.
Working Demo