Canvas save() and restore()

When working with the canvas element you can save and restore matrix transformations using the save() and restore() methods. These methods are similar to glPushMatrix() and glPopMatrix() from OpenGL – and pushMatrix()/popMatrix() from Processing. Something interesting about save() and restore() is that they also store things like fillStyle, lineWidth, strokeStyle and shadowColor… When working with save() and restore() it’s important to note that your working with a stack data structure. If you don’t know what that is, check out the wikipedia entry. Here’s a demo:


This is an example that creates an isometric shape:

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
 
var segNum = 60;
var rotation = 0, col, i2, i;
 
setInterval(function(){
  c.fillStyle = "#8193a1";
  c.fillRect(0,0,canvas.width,canvas.height);
 
  for (i = 0; i<segNum; i++){
    i2 = i * 2;
    col = i2 + 130;
    c.save();
    c.fillStyle = "rgb("+col+","+col+","+col+")";
    if (i == 0){
      c.shadowColor = "rgba(0,0,0,0.2)";
      c.shadowBlur = 30;
    }
    c.translate(200, 240 - i2);
    c.scale(1,0.5);
    c.rotate(rotation + i/100);
    c.fillRect(-50,-50,100,100);
    c.restore();
  }
  rotation+=0.05;
 
},30);


 
 
 

2 Responses to “Canvas save() and restore()”

  1. Ted
    16. February 2011 um 01:50

    Neat stuff as always Z!

  2. Zevan
    16. February 2011 um 08:21

    thanks Ted.

Leave a Reply

Spam protection by WP Captcha-Free