Summary -

In this topic, we described about the Canvas States with detailed example.

The canvas using 2D Context when drawing on HTML5, the 2D Context is in a certain state. We can set that certain state by using the 2D Context properties like fillStyle and strokeStyle. All these modifications in total is called the 2D context state.

Sometimes, we need to change the state of the 2D Context when drawing on a canvas based on the requirement. For example, we may need one strokStyle for one line and another strokeStyle for other lines. or something else.

The canvas drawing state is essentially a snapshot of entire styles and changes that consists of the followings -

  • The changes such as rotate, translate, and scale etc.
  • The existing clipping region.
  • The present values of the following attributes – globalAlpha, fillStyle, strokeStyle, lineCap, lineWidth, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline.

We can use the save() and restore() methods of the canvas context to save and restore different transformation states with the HTML5 Canvas.

Example -

Below example describes the usage of above stated methods.
<!DOCTYPE HTML>
<html>
	<head>
	</head>
	<body>
		<canvas id = "mycanvas" width="578" height="200" 
			style="border:2px solid #00d3d3;">
		</canvas>
		<script type = "text/javascript">
			var canvas  = document.getElementById("mycanvas");
			var context = canvas.getContext("2d");
			context.fillStyle  ="#329ea8";
			context.strokeStyle="#3257a8";
			context.lineWidth  = 5;
			context.fillRect(5, 5, 50, 50);
			context.strokeRect(5, 5, 50, 50);
			context.save();
			context.fillStyle = "#059bff";
			context.fillRect  (65, 5, 50, 50);
			context.strokeRect(65, 5, 50, 50);
			context.save();
			context.strokeStyle = "#87a832";
			context.fillRect  (125, 5, 50, 50);
			context.strokeRect(125, 5, 50, 50);
			context.restore();
			context.fillRect  (185, 5, 50, 50);
			context.strokeRect(185, 5, 50, 50);
			context.restore();
			context.fillRect  (245, 5, 50, 50);
			context.strokeRect(245, 5, 50, 50);
		</script>
	</body>
</html>       

Output -

Browser Support

The following browsers with versions in the table indicates the initial browser version that completely endorses the property.

Property Chrome Edge Firefox Safari Opera
states Yes 9.0 and above Yes Yes Yes