HTML5 कैनवास कैनवास की स्थिति को सहेजने और पुनर्स्थापित करने के लिए दो महत्वपूर्ण तरीके प्रदान करता है। हर बार सहेजें . कैनवास की स्थिति एक स्टैक पर संग्रहीत की जाती है विधि को कहा जाता है, और अंतिम सहेजी गई स्थिति को हर बार पुनर्स्थापना . पर स्टैक से वापस कर दिया जाता है विधि कहा जाता है।
| 1 | save() यह विधि वर्तमान स्थिति को स्टैक पर धकेलती है। |
| 2 | पुनर्स्थापित करें () यह विधि उस स्थिति के संदर्भ को पुनर्स्थापित करते हुए, स्टैक पर शीर्ष स्थिति को पॉप करती है। |
उदाहरण
आप निम्न कोड को चलाने का प्रयास कर सकते हैं कैनवास में विधियों को सहेजने और पुनर्स्थापित करने के बारे में जानें:
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script>
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// draw a rectangle with default settings
ctx.fillRect(0,0,150,150);
// Save the default state
ctx.save();
// Make changes to the settings
ctx.fillStyle = '#66FFFF'
ctx.fillRect( 15,15,120,120);
// Save the current state
ctx.save();
// Make the new changes to the settings
ctx.fillStyle = '#993333'
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90);
// Restore previous state
ctx.restore();
// Draw a rectangle with restored settings
ctx.fillRect(45,45,60,60);
// Restore original state
ctx.restore();
// Draw a rectangle with restored settings
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>