My scenario is that the Canvas width / height is changed dynamically, And I dont want to reset the Canvas. Instead I use the clearRect() as I know the bounds in which the recta开发者_StackOverflow中文版ngle has to be cleared.
Is there a way to disable the resetting of canvas when Width/Height is set again?
Is there a way to save the previous state and just load it back to the canvas exactly without re-drawing it?
I'm afraid there's no way to disable this, it is built into the canvas spec.
Section 4.8.11:
When the canvas element is created, and subsequently whenever the width and height attributes are set (whether to a new value or to the previous value), the bitmap and any associated contexts must be cleared back to their initial state and reinitialized with the newly specified coordinate space dimensions.
Yes, and GetImageData/PutImageData is one way but it is probably much slower than the following way:
Let's say your canvas is called
realCanvas
. Make a second canvas (we'll call itfakeCanvas
) that is as large as you ever intend your real canvas to be, but only make it in javascript code and never add it to the document (so no one will ever see it).Then, right before you resize
realCanvas
, do this operation:fakeCanvasContext.drawImage(realCanvas, 0, 0);
This will draw one entire canvas to another and it will happen very quickly from a performance perspective.
Once you are done with the resize you can draw the contents of fakeCanvas back onto your realCanvas.
realCanvasContext.drawImage(fakeCanvas, 0, 0);
And that's it!
If you want to get technical, you can speed up my way even more by doing this for the second draw:
realCanvasContext.drawImage(fakeCanvas, 0, 0, realCanvas.width, realCanvas.height, 0, 0, realCanvas.width, realCanvas.height);`
That way you are only copying the part that can fit onto
realCanvas
. Please note that I haven't tested the code I wrote so there might be a syntax error or two.
精彩评论