Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 restore canvas after clearing

I have a function that draws a collection of images to the canvas and it saves it after.

Then in the command line I run:

canvas.save();
canvas.clearRect(0,0,415,415);
canvas.restore();

I expect it to restore it, but it does nothing. Any help, I can't find anything on google about running in this series, and i've had this problem a few times in the past.

like image 806
Marius Miliunas Avatar asked Nov 15 '11 02:11

Marius Miliunas


2 Answers

You can use getImageData and putImageData to save and restore canvas content.

tmp = context.getImageData(0,0,415,415);
context.clearRect(0,0,415,415);
context.putImageData(tmp,0,0);
like image 103
cuixiping Avatar answered Sep 20 '22 04:09

cuixiping


You're misinterpreting what save does. It saves the state of the canvas, which is affected by rotate, translate, scale, etc. It does not save any of the actual content of the canvas. If you want to save what's actually on the canvas, try storing it in a hidden canvas. Assuming you've added the hidden canvas to the html and gotten its context object (canvas2), the following should save it:

canvas2.drawImage(canvas, 0, 0)

And then to restore it:

canvas.drawImage(canvas2, 0, 0)
like image 36
Aaron Dufour Avatar answered Sep 24 '22 04:09

Aaron Dufour