Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate canvas after pixelmanipulation

I got following problem:

I load an image into my canvas and do stuff with it (f.e. inverse the colors or more performance-needing stuff). After that I still want to be able to scale and rotate the canvas (or the manipulated image in it). That for (if I got it right) I need to redraw the image, well - the manipulation is gone then.

So: - Can I save the image somehow and redraw it after the manipulation (ctx.save() and ctx.restore() seems not working in this case) - Or do I have to rotate and scale by pixelmanipulation (wouldn't be a problem, but would be cool if canvas-transformation could do it)

Thank you for your help!

like image 853
kaljak Avatar asked Dec 07 '25 13:12

kaljak


1 Answers

You can achieve what you want using two canvas elements, drawing on one for your maniuplation and then drawing that canvas on the second to apply the rotation:

var canvas1 = document.createElement('canvas'),
    canvas2 = document.createElement('canvas'),
    ctx1 = canvas1.getContext('2d'),
    ctx2 = canvas2.getContext('2d');

/// use ctx1 to perform whatever manipulation you want, and then...

/// start
ctx2.save();
/// shift our "hotspot" to the center
ctx2.translate(canvas2.width / 2, canvas2.height / 2);
/// rotate 45 degrees clockwise.. obviously you can do what you want here
/// scale, fade, flip, stretch, rotate... whatever 
ctx2.rotate(Math.PI / 4);
/// draw your first canvas with it's manipulated image on to the second
/// along with it's rotation
ctx2.drawImage( canvas1, 0,0 );
/// all done
ctx2.restore();

I find the above easier to work with, however you can also use the following, which will grab out / put back the current image data of a canvas element:

ctx.getImageData();
ctx.putImageData();

You can find out how to use these here:

https://developer.mozilla.org/en-US/docs/HTML/Canvas/Pixel_manipulation_with_canvas

http://www.w3schools.com/html5/canvas_getimagedata.asp

like image 155
Pebbl Avatar answered Dec 10 '25 04:12

Pebbl