Canvas Save and restore playground

by Michał Belka

HTML

<canvas id="canvas" width="300" height="300"></canvas>

CSS

canvas {
    border: 1px red solid;
}

JavaScript

var ctx = document.getElementById('canvas').getContext('2d');
for (var x = 0.5; x < 300; x += 10) {ctx.moveTo(x, 0);ctx.lineTo(x, 300);}for (var y = 0.5; y < 300; y += 10) {ctx.moveTo(0, y);ctx.lineTo(300, y);}ctx.strokeStyle = "#ddd";ctx.stroke(); // Grid

ctx.save();
ctx.fillRect(10,10,100,100);

ctx.fillStyle = 'rgb(10, 100, 200)';
ctx.save();
ctx.fillRect(30, 30, 100, 100);

ctx.fillStyle = 'rgb(10, 200, 100)';
ctx.fillRect(50, 50, 100, 100);

ctx.restore();
ctx.fillRect(70, 70, 100, 100);

ctx.restore();
ctx.fillRect(90, 90, 100, 100);

// WARNING
// For simple usage, like this one, saving values in variables is quicker.
// ctx.save() is saving a LOT of information therefore use with caution.