HTML5 canvas มี 2 เมธอดสำคัญ save และ restore canvas states Canvas states เก็บบน stack ทุกครั้งที่เรียก save และ state ล่าสุดจะถูก pop จาก stack ทุกครั้งที่เรียก restore
| Sr.No. | Method and Description |
|---|---|
| 1 | save() Push current state onto stack |
| 2 | restore() Pop top state from stack restore context to that state |
ตัวอย่าง
ลองรันโค้ดเรียนรู้ save และ restore:
<!DOCTYPE HTML>
<html>
<head>
<style>
#test { width: 100px; height: 100px; margin: 0px auto; }
</style>
<script>
function drawShape() {
var canvas = document.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 150, 150);
ctx.save();
ctx.fillStyle = '#66FFFF';
ctx.fillRect(15, 15, 120, 120);
ctx.save();
ctx.fillStyle = '#993333';
ctx.globalAlpha = 0.5;
ctx.fillRect(30, 30, 90, 90);
ctx.restore();
ctx.fillRect(45, 45, 60, 60);
ctx.restore();
ctx.fillRect(40, 40, 90, 90);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>