HTML5 Game - Canvas Drawing State

What is the canvas drawing state?

The canvas drawing state refers to a whole range of properties of the 2d rendering context.

The full list of properties of the canvas drawing state are:

  • transformation matrix
  • clipping region,
  • globalAlpha,
  • globalCompositeOperation,
  • strokeStyle,
  • fillStyle,
  • lineWidth,
  • lineCap,
  • lineJoin,
  • miterLimit,
  • shadowOffsetX,
  • shadowOffsetY,
  • shadowBlur,
  • shadowColor,
  • font,
  • textAlign,
  • textBaseline.

To save the drawing state

context.save(); // Save the canvas state  

To restore the drawing state:

context.restore(); // Restore the canvas state  

The following code shows how to save and restore multiple drawing states.

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Pushing canvas further</title>
    <meta charset="utf-8">
    /*from  w  w  w .  j  av  a  2 s. c  o m*/
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        context.fillStyle = "rgb(255, 0, 0)";
        context.save(); // Save the canvas state
        context.fillRect(50, 50, 100, 100); // Red square
        
        context.fillStyle = "rgb(0, 0, 255)";
        context.save();
        context.fillRect(200, 50, 100, 100); // Blue square
        
        context.restore(); // Restore the canvas state
        context.fillRect(350, 50, 100, 100); // Blue square
        
        context.restore(); // Restore the canvas state
        context.fillRect(50, 200, 100, 100); // Red square
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topics