Restore a drawing state in JavaScript
Description
The following code shows how to restore a drawing state.
Example
<!-- ww w . j ava2 s .com-->
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// draw rectangle
context.beginPath();
context.rect(150, 30, 130, 130);
context.fillStyle = "blue";
context.fill();
// wrap circle drawing code with save-restore combination
context.save();
context.globalAlpha = 0.5; // set global alpha
context.beginPath();
context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
context.restore();
// draw another rectangle
context.beginPath();
context.rect(canvas.width - (150 + 130), canvas.height - (30 + 130), 130, 130);
context.fill();
};
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
</canvas>
</body>
</html>
The code above generates the following result.
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
Set color to transparency when drawing on c...
Set shadow color and blur in JavaScript
Use image as the fill pattern in JavaScript
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