HTML5 Canvas Transformation State Stack Tutorial

May 19, 2011

To save and restore different transformation states with the HTML5 Canvas, we can use the save() and restore() methods of the canvas context.

context.save();
context.restore();

In this tutorial, we’ll save the transformation state by pushing the state onto the state stack immediately before each transformation, draw a blue rectangle, restore and pop off the last transformation state and draw a red rectangle, restore and pop off the last transformation state and draw a yellow rectangle, and then finally restore and pop off the last transformation state and draw a green rectangle.

HTML5 Canvas Transformation State Stack Example


Open in new window

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    var rectWidth = 150;
    var rectHeight = 75;

    context.save(); // save state 1
    context.translate(canvas.width / 2, canvas.height / 2);

    context.save(); // save state 2
    context.rotate(Math.PI / 4);

    context.save(); // save state 3
    context.scale(2, 2);

    context.fillStyle = "blue";
    context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);

    context.restore(); // restore state 3
    context.fillStyle = "red";
    context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);

    context.restore(); // restore state 2
    context.fillStyle = "yellow";
    context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);

    context.restore(); // restore state 1
    context.fillStyle = "green";
    context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
};


By Eric Rowell at html5canvastutorials.com

HTML5 Canvas HTML5 Canvas Transformation State Stack, html5 canvas tutorials,


Comments

blog comments powered by Disqus