HTML5 Game - Saving the Canvas State

Introduction

The canvas state means settings such as the strokeStyle, fillStyle, lineWidth, lineCap, shadowOffsetX, shadowOffsetY, shadowBlur, and shadowColor properties and a few other settings.

To save a snapshot of the canvas settings, use the two methods: save() and restore().

The save() method saves a canvas state, whereas the restore() method restores a previously saved state.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*w  ww . j  ava2 s . c om*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        //default state 
        context.lineWidth = 5; 
        context.fillStyle = 'blue'; 
        context.fillRect(10, 120, 150, 50); 
        context.save(); 
        //change state 
        context.lineWidth = 10; 
        context.fillStyle = 'red'; 
        context.fillRect(20, 130, 150, 50); 
        //restore state 
        context.restore(); 
        context.fillRect(30, 140, 150, 50); 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

The first canvas settings such as lineWidth and fillStyle are set and a rectangle is drawn.

You save these settings using the save() method.

Then, we change the canvas settings to new values, and a rectangle is drawn.

Finally, before drawing a third rectangle, we restore the canvas settings using restore().

Related Topic