下から上へ円が移動するアニメーション
Canvas 上の最下部から最上部に向けて、円が移動していくアニメーションを作った。
function canvasApp() { var canvas = document.getElementById('stage'); var ctx = canvas.getContext('2d'); var x = canvas.width/2; var y = canvas.height; var dx = 0; var dy = -1; var r = 20; startUp(); function drawScreen() { // canvas の初期化 ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'black'; ctx.beginPath(); ctx.arc(x, y, r, (Math.PI/180)*0, (Math.PI/180)*360, false); x = x+dx; y = y+dy; ctx.fill(); } function startUp() { var timer = setTimeout(function() { startUp(); }, 10); if (y == 0) { clearTimeout(timer); } drawScreen(); } }
2回目以降の描画の際には、drawScreen
内で clearRect
を使って Canvas 上の描画を一度真っ白にしないと円が移動しているようには見えない。前の描画処理の内容が残ると線が下から上に引かれる用に見えてしまう。
他は特に工夫したところはなくて、ドットインストールや HTML5 Canvas の本で学んだことを応用しながら作ってみた。
今は直線にしか移動させてないけど、次は移動の途中で動きの方向を変えたりさせてみたい。