Save and restore Canvas states with button action in JavaScript

Description

The following code shows how to save and restore Canvas states with button action.

Example


<!--from   w ww.  ja  va2s .  c  o  m-->
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="500" height="140" preload="auto"></canvas>
<div>
<button>Save</button>
<button>Restore</button>
</div>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
var grad = ctx.createLinearGradient(500, 0, 500, 140);
grad.addColorStop(0, "red");
grad.addColorStop(0.5, "white");
grad.addColorStop(1, "black");
var colors = [ "blue", grad, "red", "green", "yellow", "black", "grey" ];
var cIndex = 0;
ctx.fillStyle = colors[cIndex];
draw();
var buttons = document.getElementsByTagName("button");

for ( var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
switch (e.target.innerHTML) {
case 'Save':
ctx.save();
cIndex = (cIndex + 1) % colors.length;
ctx.fillStyle = colors[cIndex];
draw();
break;
case 'Restore':
cIndex = Math.max(0, cIndex - 1);
ctx.restore();
draw();
break;
}
}
function draw() {
ctx.fillRect(0, 0, 500, 400);
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Save and restore Canvas states with button action in JavaScript
Home »
  Javascript Tutorial »
    Canvas »
      Canvas Draw
Javascript Tutorial Canvas Draw
Change the stroke style in JavaScript
Clip a region in JavaScript
Control line width in JavaScript
Create Radial Gradient on HTML5 canvas in J...
Create a rainbow radial gradient in JavaScr...
Create linear gradient in JavaScript
Draw an image on HTML5 Canvas in JavaScript
Draw transparent shapes on HTML5 Canvas in ...
Get canvas context in JavaScript
Restore a drawing state in JavaScript
Save and restore Canvas states with button ...
Set color to transparency when drawing on c...
Set shadow color and blur in JavaScript
Use image as the fill pattern in JavaScript