2013年1月14日
前記事で二線間の交点に円弧を描く「arcTo」を使った方法(メソッド)を先に紹介したけれど、円や円弧を描く「arc」メソッドもある。ただ円を描くだけでは面白くないので、インターバルタイマーを使って、ランダムに円を描いてみよう。
<script type="text/javascript"> window.onload = function(){ var canvas = document.getElementById('myGraph'); if (! canvas || ! canvas.getContext){return false;}; ctx = canvas.getContext('2d'); w = canvas.width; h = canvas.height; drawCircle(); }; // タイマーを設定(1秒=1000ミリ秒) function setTimer(){ // 1/10秒ごとに、drawCircle関数を呼び出す timerID = setInterval("drawCircle()", 100); }; // タイマーを解除 function stopTimer(){ clearInterval(timerID); }; // ランダムに円を描く function drawCircle(){ // Canvasを指定色で塗りつぶす(描いた円を消す) ctx.lineWidth = 1; ctx.fillStyle = "#3366cc"; ctx.fillRect(0, 0, w, h); ctx.fill(); // 10個の円を描く for (i=0; i<10; i++) { var x = parseInt(Math.random()*w); var y = parseInt(Math.random()*h); var r = parseInt(Math.random()*90+10); ctx.strokeStyle = "#ffffff"; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI*2, false); ctx.closePath(); ctx.stroke(); }; }; </script>