今日の課題:Canvasの状態セーブ
<!DOCTYPE html>
<html>
<head>
<title>HTML5の練習@ヒッキープログラミングスレ</title>
<style type="text/css">
body { background-color: silver; }
canvas { background-color: white; }
</style>
</head>
<body>
<h4>状態セーブ</h4>
<canvas id="mycanvas" width="640" height="480"></canvas>
<script language="javascript" type="text/javascript">
function mydraw() {
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 150, 150);
ctx.fillStyle = 'blue';
ctx.save(); // クリップや色がセーブされる
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 100);
ctx.lineTo(150, 200);
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.rect(110, 100, 50, 100);
ctx.fill();
ctx.restore(); // クリップが解除される!!色が戻る!
ctx.beginPath();
ctx.fillRect(400, 100, 100, 100);
}
mydraw();
</script>
</body>
</html>
- save() でクリッピングの状態や色などの情報が保存される
- restore() save()したときのクリッピングの状態や色を戻せる
最終更新:2016年05月19日 05:26