HTML5 > Canvasで丸を描く

今日の課題: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');
                var rad = function (d) { return 2.0 * Math.PI * (d / 360.0) ; };
 
                ctx.strokeStyle = 'red';
 
                var x = [100, 300, 500];
                var y = 100;
 
                // 左
                ctx.beginPath();
                ctx.arc(x[0], y, 50, rad(0), rad(360), false);
                ctx.stroke();
                // 真ん中
                ctx.beginPath();
                ctx.arc(x[1], y, 50, rad(0), rad(280), false);
                ctx.stroke();
                // 右
                ctx.beginPath();
                ctx.arc(x[2], y, 50, rad(0), rad(280), true);
                ctx.stroke();
 
                ctx.fillStyle = 'blue';
                y += 150;
 
                // 左
                ctx.beginPath();
                ctx.arc(x[0], y, 50, rad(0), rad(360), false);
                ctx.fill();
                // 真ん中
                ctx.beginPath();
                ctx.arc(x[1], y, 50, rad(0), rad(280), false);
                ctx.fill();
                // 右
                ctx.beginPath();
                ctx.arc(x[2], y, 50, rad(0), rad(280), true);
                ctx.fill();
 
 
                ctx.strokeStyle = 'green';
                ctx.fillStyle = 'green';
                y += 150;
 
                ctx.beginPath();
                ctx.arc(x[0], y, 50, rad(0), rad(280), false);
                ctx.closePath();
                ctx.stroke();
 
                ctx.beginPath();
                ctx.moveTo(x[1], y);
                ctx.arc(x[1], y, 50, rad(0), rad(280), false);
                ctx.closePath();
                ctx.stroke();
 
                ctx.beginPath();
                ctx.moveTo(x[2] + 80, y - 100);
                ctx.arc(x[2], y, 50, rad(0), rad(280), false);
                ctx.closePath();
                ctx.stroke();
 
            }
 
            mydraw();
 
        </script>
    </body>
</html>
 


  • arc(x,y,r,s,e,a) 円弧を描く。x,yは中心座標、rは半径、s,eは弧の始点と終点を中心点真右を基準にラジアン角度で、aは右周りか左周りか
  • ラジアン角度は普通の角度を円周率の2倍を掛けて360で割ると求まる。
  • arcはlineToと同じようにbeginPath()やstroke()やfill()やclosePath()などを組み合わせて使う
  • arcは他のarcやlineToやmoveToのカレント座標の影響を受けるので気をつけないと余計な線が描かれる
    (beginPath()などで回避するとよいかも)

タグ:

+ タグ編集
  • タグ:
最終更新:2016年05月09日 04:44