lundi 19 août 2013

What's the role of save and restore in canvas context

When I started to work with canvas I was wondering the role of save and restore in canvas.

 Save store the drawing state of the context, do interesting things with a new drawing state and restore it when you have finished.

 Let's take an example to understand it. Imagine you want to build an ellipse and a circle. For the circle no problem :


But there's no function for the ellipse except if you decide to change the scale of the drawing context.


 The drawing state of the canvas has been changed with ctx.scale(1,0.6) which flat the coordinate system on the y axis, creating an ellipse.

So why not creating a circle and an ellipse this way :


As you can see I made an ellipse and a circle but they don't have the same center because when I scale vertically the drawing state it reduced the coordinate of the y center. Beside I kind of restore the drawing state with this code ctx.scale(1, 1/0.6); which is error prone because you may forget a change you didn't undo.

Here is a solution with translate and save/restore


 Now we have an ellipse and a circle with the same center.






Aucun commentaire: