HTML Canvas を利用して円を描画するコードを紹介します。
プログラム
コード
以下のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">
function draw() {
var canvas = document.getElementById('SimpleCanvas');
if ( ! canvas || ! canvas.getContext ) {
return false;
}
var cx = 360;
var cy = 400;
var radius = 36;
var context = canvas.getContext('2d');
context.beginPath();
context.arc(cx, cy, radius, 0, 2 * Math.PI, false);
context.fillStyle = '#9fd9ef';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#00477d';
context.stroke();
}
</script>
</head>
<body onload="draw()" style="background-color:#D0D0D0;">
<canvas id="SimpleCanvas" width="640" height="480" style="background-color:#FFFFFF;"></canvas>
<div>Canvas Demo</div>
</body>
</html>
実行結果
補足
arc()メソッドで与える円の座標は円の中心座標になります。
先のHTMLファイルで、描画部を下図のコードにします。
function draw() {
var canvas = document.getElementById('SimpleCanvas');
if ( ! canvas || ! canvas.getContext ) {
return false;
}
var cx = 360;
var cy = 400;
var radius = 36;
var context = canvas.getContext('2d');
context.beginPath();
context.arc(cx, cy, radius, 0, 2 * Math.PI, false);
context.fillStyle = '#9fd9ef';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#00477d';
context.stroke();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(cx, cy);
context.stroke();
}
上記のコードの表示結果は下図となります。中心座標は円の中心であることがわかります。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2015-10-06
作成日: 2015-09-29