Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

บันทึกและกู้คืน State ของ HTML5 Canvas (Save/Restore)

Canvas State Stack: save() และ restore()

State ประกอบด้วย: Transformations, Styles (fillStyle, strokeStyle, lineWidth, font, etc.), Clipping Region

เมธอด

Methodคำอธิบาย
save()Push Current State ลง Stack
restore()Pop State สุดท้ายออกมา ใช้แทน Current State

ตัวอย่างสมบูรณ์

<!DOCTYPE HTML>
<html>
<head>
  <style>#test { width:100px; height:100px; margin:0 auto; }</style>
  <script>
    function drawShape() {
        var canvas = document.getElementById('mycanvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            
            // 1. วาดสี่เหลี่ยมปกติ
            ctx.fillRect(0, 0, 150, 150);
            
            // 2. Save State 1 (Default)
            ctx.save();
            
            // 3. เปลี่ยน Style วาดสี่เหลี่ยมเล็ก
            ctx.fillStyle = '#66FFFF';
            ctx.fillRect(15, 15, 120, 120);
            
            // 4. Save State 2
            ctx.save();
            
            // 5. เปลี่ยน Style อีก (Alpha)
            ctx.fillStyle = '#993333';
            ctx.globalAlpha = 0.5;
            ctx.fillRect(30, 30, 90, 90);
            
            // 6. Restore State 2 -> กลับไป State 1
            ctx.restore();
            ctx.fillRect(45, 45, 60, 60); // ใช้ Style State 1
            
            // 7. Restore State 1 -> กลับไป Default
            ctx.restore();
            ctx.fillRect(40, 40, 90, 90); // ใช้ Default Style
        }
    }
  </script>
</head>
<body id="test" onload="drawShape()">
  <canvas id="mycanvas"></canvas>
</body>
</html>

Stack: LIFO (Last In First Out) ใช้จัดการ State ซ้อนกันได้หลายระดับ