The restore()
method
reset the canvas by "popping" the last state saved to the stack.
restore() |
Yes | Yes | Yes | Yes | Yes |
context.restore()
The following code pushes and pops the drawing states.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
var stage= document.getElementById('canvas');
var ctx = stage.getContext('2d');
<!-- w ww. j a va 2s .c o m-->
// Save previous origin (among other things)
ctx.save();
// Move origin to "middle" of canvas
ctx.translate(200,200)
ctx.fillStyle = "red";
// draw rectange with x & y relative to new origin
ctx.fillRect(-50, -50, 100, 100);
// Reset origin
ctx.restore();
ctx.fillStyle = "blue";
// draw rectange with x & y relative to original origin
ctx.fillRect(0, 0, 50, 50);
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to save and restore several drawing state.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script type='text/javascript'>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
<!-- w ww.j ava 2s . c o m-->
var rectWidth = 150;
var rectHeight = 75;
context.save(); // save state 1
context.translate(canvas.width / 2, canvas.height / 2);
context.save(); // save state 2
context.rotate(Math.PI / 4);
context.save(); // save state 3
context.scale(2, 2);
context.fillStyle = "blue";
context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
context.restore(); // restore state 3
context.fillStyle = "red";
context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
context.restore(); // restore state 2
context.fillStyle = "yellow";
context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
context.restore(); // restore state 1
context.fillStyle = "green";
context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
</script>
</body>
</html>
The code above is rendered as follows: