Drawing image in Canvas at an angle WITHOUT rotating the Canvas
I am drawing an image in HTML 5 using canvas in JavaScript. I need to draw it at a rotated angle. I know this can be done by applying rotate(angle) function using the context of the canvas. But I need to do this without rotating th开发者_JS百科e canvas itself.
Kindly suggest possible approach for this if it's possible.
You can actually draw whatever you want to rotate into an offscreen canvas and draw that into your main canvas. I borrowed this code from a Google IO Talk:
rotateAndCache = function(image,angle) {
var offscreenCanvas = document.createElement('canvas');
var offscreenCtx = offscreenCanvas.getContext('2d');
var size = Math.max(image.width, image.height);
offscreenCanvas.width = size;
offscreenCanvas.height = size;
offscreenCtx.translate(size/2, size/2);
offscreenCtx.rotate(angle + Math.PI/2);
offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2));
return offscreenCanvas;
}
then cache it with:
rotobj = rotateAndCache(myimg,myangle)
and in your drawcode:
mycontext.drawImage(rotobj,x_coord,y_coord)
This is only useful if you have an object that is rotated by an angle only once and is subsequently only subject to transformations.
When you apply transformation on canvas you don't rotate canvas. you just tell that all you.are going to draw will be transformed in particular way. If you want to avoid transformation to affect other commands use save()
and restore()
methods. They allow to save and restore settings of the canvas.
ctx.save();
ctx.rotate(30);
ctx.drawImage();
ctx.restore();
I've upvoted @PeterT-- great snippet and works well-- thanks for that! I did have to make 3 small changes to get this to work for me:
1. the max of width and height isn't enough: if you think about rotating a square, you need a circle whose diameter is the diagonal of the square (var diam
).
2. the canvas needs to be translated back (or use save/restore).
3. the object x and y coordinates have to be adjusted for the canvas size.
So I ended up with:
rotateAndCache = function(image,angle) {
var offscreenCanvas = document.createElement('canvas');
var offscreenCtx = offscreenCanvas.getContext('2d');
var size = Math.max(image.width, image.height);
var diam = 2*((size/2)*Math.sqrt(2)); // needs to be saved
offscreenCanvas.width = diam;
offscreenCanvas.height = diam;
offscreenCtx.translate(diam/2, diam/2);
offscreenCtx.rotate(angle);
offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2));
offscreenCtx.translate(-diam/2, -diam/2);
return offscreenCanvas;
}
And the adjusted draw position (needs to be saved in rotateAndCache
):
mycontext.drawImage(rotobj,x-(diam-width)/2,y-(diam-height)/2);
That's not possible and you probably don't need it. Try this:
context.save() // Save current state (includes transformations)
context.rotate()
... draw image ...
context.restore() // Restore state
精彩评论