Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reset the scale of a canvas' context?

I have a variable, context, which is the 2d context of my canvas.

var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');

Calling context.scale(x,y) multiple times scales the context depending on what the previous scales did. For example, context.scale(2,2); context.scale(2,2) is equivalent to context.scale(4,4). How can I reset the context's scale?

like image 735
Jonah Avatar asked Nov 13 '15 14:11

Jonah


People also ask

How do I reset my canvas?

From the course navigation menu, select Settings. In the "Settings" sidebar at the right, select Delete All Course Content. You will be prompted to confirm. To proceed, click Reset Course Content, or click Cancel to cancel.

How do you scale on canvas?

The scale() method scales the current drawing, bigger or smaller. Note: If you scale a drawing, all future drawings will also be scaled. The positioning will also be scaled. If you scale(2,2); drawings will be positioned twice as far from the left and top of the canvas as you specify.

What does CTX restore do?

The ctx. restore() method of the Canvas 2D API restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing.

How do you clear canvas and redraw?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.


Video Answer


1 Answers

scale will multiply the current transform matrix by a scale matrix, so indeed, these scale factors multiply. You can use the state stack to save and restore the current transform:

context.save();
context.scale(2, 2);
... // anything drawn here is twice as big
context.restore();

Alternatively, you can reset the transform by loading the identity matrix directly:

context.scale(2, 2);
...
context.setTransform(1, 0, 0, 1, 0, 0);
like image 50
Thomas Avatar answered Sep 28 '22 16:09

Thomas