Html5-canvas-states
提供:Dev Guides
HTML5 Canvas-状態の保存と復元
HTML5キャンバスは、キャンバスの状態を保存および復元するための2つの重要な方法を提供します。 キャンバスの描画状態は、基本的に適用されているすべてのスタイルと変換のスナップショットであり、以下で構成されています-
- 平行移動、回転、拡大縮小などの変換
- 現在のクリッピング領域。
- 次の属性の現在の値-strokeStyle、fillStyle、globalAlpha、lineWidth、lineCap、lineJoin、miterLimit、shadowOffsetX、shadowOffsetY、shadowBlur、shadowColor、globalCompositeOperation、font、textAlign、textBaseline.
Canvasの状態は save メソッドが呼び出されるたびにスタックに保存され、 restore メソッドが呼び出されるたびに最後に保存された状態がスタックから返されます。
Sr.No. | Method and Description |
---|---|
1 |
save() このメソッドは、現在の状態をスタックにプッシュします。 |
2 |
restore() このメソッドは、スタックの一番上の状態をポップし、コンテキストをその状態に復元します。 |
例
以下は、上記のメソッドを使用して_restore_がどのように呼び出され、元の状態を復元し、最後の長方形が再び黒で描画されるかを示す簡単な例です。
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
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>
上記の例では、次の結果が生成されます-