How To Save/Restore Html5 Canvas Context State Example

When you develop an Html5 app, you sometimes need to save the current canvas state data ( such as color, line width, font .etc ) before drawing another shape. And after drawing another shape, you can restore the canvas state to the saved one and continue drawing. This article will tell you how to implement it.

1. How To Save/Restore Canvas State In Html5.

  1. The Html5 canvas context’s save() method can be used to save the current canvas state.
  2. The Html5 canvas context’s restore() method can be used to restore the current canvas state.

2. Save / Restore Html5 Canvas State Example.

  1. Below is the example web page picture.
  2. When you click the Draw Rectangle button, it will first set the fill color to red and draw the big red rectangle, then call the canvas context’s save() method to save the canvas state.
  3. Then it will set the fill color to green and draw a green square in the big red rectangle.
  4. Then it will call the canvas context’s restore() method to restore the canvas state ( restore the fill color to red ) and draw the small red square inside the green square.
  5. This example contains 2 source files, html5-canvas-context-state-example.html, html5-canvas-context-state-example.js.
  6. html5-canvas-context-state-example.html.
    <!DOCTYPE html>
    <meta charset="ISO-8859-1">
    <title>How To Save/Restore Html5 Canvas Context State Example</title>
    <script type="text/javascript" src="html5-canvas-context-state-example.js" charset="utf-8"></script>
    <h3>How To Save/Restore Html5 Canvas Context State Example.</h3>
    <div style="display:block;margin-top: 10px;">
        <input type="button" value="Draw Rectangle" onclick="drawRectangle('canvas1')" />
    <canvas id="canvas1"></canvas>
  7. html5-canvas-context-state-example.js

    function drawRectangle(canvasId){
         // Get the html canvas object.
        var canvas = document.getElementById(canvasId);
            alert("Can not find the html element with element id " + canvasId);
            return false;
        canvas.width = 600;
        canvas.height = 300; = 'block'; = 'blue';
        ctx = canvas.getContext('2d');
        ctx.fillStyle = 'red';
        ctx.fillStyle = 'green';

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.