I am experimenting with animation in <canvas>
and can't work out how to draw an image at an angle. The desired effect is a few images drawn as usual, with one image rotating slowly. (This image is not at the centre of the screen, if that makes any difference).
views:
151answers:
1
A:
You need to modify the transformation matrix before drawing the image that you want rotated.
Assume image points to an HTMLImageElement object.
var x = canvas.width / 2;
var y = canvas.height / 2;
var width = image.width;
var height = image.height;
context.translate(x, y);
context.rotate(angleInRadians);
context.drawImage(image, -width / 2, -height / 2, width, height);
context.rotate(-angleInRadians);
context.translate(-x, -y);
The x, y coordinates is the center of the image on the canvas.
Jakub Wieczorek
2010-09-25 10:48:22
instead of rotating/translating at the end, you could do a `context.save()` and `context.restore()` before and after you do the transformations and drawing.
Matthew Crumley
2010-09-25 15:53:30
While using save()/restore() may seem cleaner, it would be much more inefficient. The engine will have to store/restore all the context properties, not just the ones we're manipulating here. That matters in a sensitive code path.
Jakub Wieczorek
2010-09-25 17:39:28