I often see the following code
canvas.save(). canvas translate or rotate some drawing canvas.restore
I don't understand why we save and then restore. What's the point of undoing what we just did! I am sure I am missing something here Thanks
This allows you to restore the state before the most recent entry on the save stack, i.e. it "Pops the current save stack".
Using canvas. save() and canvas. restore() is a ridiculously easy way to simplify that process. By doing adjustments that apply to the Canvas within a save/restore block, you're effectively isolating said adjustments so that whatever you want to draw next won't be affected by what you're drawing now.
The context. restore() method restores the most recently saved drawing state by popping it from the stack. The drawing state is how the context remembers which fillStyle we are using and the position and orientation of the coordinate system.
save() method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack.
I understand this question is a bit dated, but for anyone still looking for an answer I can ELI5;
Imagine the canvas is a piece of paper, and you're tasked with drawing a picture of a robot right side up, at the bottom, and another robot upside down, slightly moved to the right, and about 40% smaller at the top. Something like this;
How would you start? What's easier to do first?
You would probably draw the bigger robot at the bottom first since it's right-side up and it's a lot easier to draw in the direction that feels more natural. So you've got the first one done, now how do you approach the second upside down robot?
or
This is what canvas.save()
and canvas.restore()
do, they allow you to modify your canvas in any way that makes it easier for you to draw what you need. You don't need to use these methods, but they sure do simplify a lot of the process. The above would look something like
drawRobot() canvas.save() canvas.rotate(180) canvas.translate(100, 0) canvas.scale(40,40) drawRobot() canvas.restore()
If we look at the restore()
documentation it says
is used to remove all modifications to the matrix/clip state since the last save call
and to see what those modifications are we take a look at save()
it says
translate, scale, rotate, skew, concat or clipRect, clipPath
Well look at that, we did in fact use translate
rotate
and scale
but we also did call drawRobot()
so wouldn't calling restore
erase our drawing? No, because it doesn't affect the drawing, only the modifications. So when we call restore
it will return our canvas to the state that it was in before we started the second drawing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With