Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the canvas itself.

Kindly suggest possible approach for this if it's possible.

like image 223
Vinayak Avatar asked Jun 01 '11 09:06

Vinayak


2 Answers

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.

like image 183
PeterT Avatar answered Nov 04 '22 13:11

PeterT


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();
like image 25
bjornd Avatar answered Nov 04 '22 12:11

bjornd