Canvas State: HTML5

Today lets learn about canvas states, which will come handy once we start drawing complex shapes/graphics. Canvas state keeps track of current values of lineWidth, strokeStyle, fillStyle, lineCap, transformation matrix, clipping regions etc.

Each time we save a state, it’s pushed onto a stack of saved states from which we can restore the state later.

HTML file
index.html




Canvas: HTML5





 




HTML5 document with a canvas element which has an id and 200px width and height.
It’s also attached with an external stylesheet and a javascript file.

StyleSheet file
myStyle.css

canvas {
 border: 2px dotted black;
}

Here we’re selecting canvas element and assigning it a 2px thick black dotted border.

JavaScript file
myScript.js

  context.fillStyle   = "red";
  context.fillRect(10, 10, 50, 50);
  context.save();
  
  context.fillStyle   = "blue";
  context.fillRect(20, 20, 75, 75);
  

  context.restore();
  context.fillRect(30, 30, 100, 100);

We have 3 rectangle boxes.
First one is filled with red color.
Second one is filled with blue color.

Using save() method, we have saved the fillStyle property value.
Now we restore fillStyle property before drawing the third rectangle.
Saved canvas state has fillStyle as red, so our third rectangle gets red color.

JavaScript file
myScript.js

  context.fillStyle   = "red";
  context.fillRect(10, 10, 50, 50);
  context.save();
  
  context.fillStyle   = "blue";
  context.fillRect(20, 20, 75, 75);
  context.save();
  
  context.restore();
  context.restore();
  context.fillRect(30, 30, 100, 100);

Here we’re saving canvas states twice.

Canvas State Stack
blue 2nd in.

red 1st in.

Canvas State Calls
1st restore call blue

2nd restore call red

Hence, now third rectangle will be red colored.

Canvas State: HTML5



YouTube Link: https://www.youtube.com/watch?v=1oBlAhoa9zI [Watch the Video In Full Screen.]



Full JavaScript Code
myScript.js

window.onload = canvas;

function canvas()
{
 var myCanvas = document.getElementById("myCanvas");
 
 if( myCanvas && myCanvas.getContext("2d") ) 
 {
  var context         = myCanvas.getContext("2d");
  
  context.fillStyle   = "red";
  context.fillRect(10, 10, 50, 50);
  context.save();
  
  context.fillStyle   = "blue";
  context.fillRect(20, 20, 75, 75);
  context.save();
  
  context.restore();
  context.restore();
  context.fillRect(30, 30, 100, 100);

 }
}

Related read:
Canvas Basics: HTML5
Draw Rectangle: HTML5 Canvas

Instantly we could think of building “undo” feature for our drawing board application with the help of canvas state stack!