0

I have a canvas which I convert to a image like so,

var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.src = can.toDataURL();

I need to rotate this image now? Is it possible?

Usama Rehan
  • 175
  • 4
  • 16
  • sorry,I dont think this is a duplicate. I need this to be done in js not in css. Because I transfer the image to new window when it is done rotating. – Usama Rehan Feb 21 '17 at 14:04
  • The second answer (http://stackoverflow.com/a/29398757/1693593) where canvas size is reflected relative to rotation, is probably what you want in your case. –  Feb 21 '17 at 15:17
  • 1
    Solved it thanks :) – Usama Rehan Feb 22 '17 at 05:13

1 Answers1

1

You need to create a new canvas, rotate it's 2dDrawingContext, draw your image data to it, then set that as the source

var canvas = document.createElement('canvas');
var ctx2 = canvas.getContext('2d');
ctx2.rotate(Math.PI/2);
ctx2.putImageData(ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height), 0, 0);

From there you can then call ctx2.toDataURL() and slap it in your image.

Kyle
  • 2,946
  • 1
  • 13
  • 11