概要: このチュートリアルでは、JavaScriptのarc()
メソッドを使用して円弧を描く方法を学習します。
JavaScript arc()メソッド入門
arc()
はCanvas 2D APIのメソッドです。arc()
メソッドを使用すると、円弧を描画できます。
以下にarc()
メソッドの構文を示します。
ctx.arc(x, y, radius, startAngle, endAngle [, antiClockwise])
Code language: CSS (css)
arc()
メソッドは、(x,y)
を中心とし、半径radius
の円弧を描画します。
円弧はstartAngle
で始まり、endAngle
で終わります。startAngle
とendAngle
はどちらもラジアンで指定します。
π ラジアン = 180度
なので、1ラジアンは約π/ 180
度です。円周は360
度、つまり2 * π ラジアンです。JavaScriptでは、π = Math.PI
です。
デフォルトでは、パスは時計回りに描画されます。antiClockwise
をfalse
に設定すると、時計と反対方向に描画されます。
arc()
メソッドを呼び出す前に、新しいパスを開始するためにbeginPath()
を呼び出す必要があります。
arc()
メソッドを呼び出した後、stroke()
メソッドを呼び出してstrokeStyle
で円弧にストロークを適用できます。また、fill()
メソッドを呼び出してfillStyle
で円弧を塗りつぶすこともできます。
円弧の幅を設定するには、lineWidth
プロパティを使用します。例:
ctx.lineWidth = 5;
JavaScript arcの例
JavaScriptのarc()
メソッドを使用して円弧を描画する例をいくつか見てみましょう。
円の描画
以下のindex.html
には、キャンバス要素が含まれています。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript arc Demo</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>JavaScript arc Demo</h1>
<canvas id="canvas" height="400" width="500">
</canvas>
<script src="js/app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
そして、以下はarc()メソッドを使用してキャンバスの中心に円を描画します。
const canvas = document.querySelector('#canvas');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.fillStyle = 'rgba(255,0,0,0.1)';
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, 100, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
}
Code language: JavaScript (javascript)
仕組み
- まず、
querySelector()
メソッドを使用してキャンバスを選択します。 - 次に、Canvas APIがサポートされている場合、2D描画コンテキストを取得します。
- その後、2D描画コンテキストの
strokeStyle
、fillStyle
、lineWidth
プロパティを使用して、ストローク、塗りつぶし、線幅を設定します。 - その後、
beginPath()
とarc()
メソッドを使用して、半径100ピクセルの円をキャンバスの中心に描画します。円は、開始角度が0で終了角度が2 * Math.PI
の円弧です。 - 最後に、
stroke()
メソッドとfill()
メソッドを呼び出して、ストロークと塗りつぶしを適用します。
出力結果は次の画像のようになります。

そして、こちらがライブページへのリンクです。
次のコードは、同じ半径の6つの円弧を描画します。すべての円弧の開始角度は0です。
const canvas = document.querySelector('#canvas');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'green';
ctx.lineWidth = 2;
const x = 40,
y = canvas.height / 2,
space = 10,
radius = 30,
arcCount = 6;
for (let i = 0; i < arcCount; i++) {
ctx.beginPath();
ctx.arc(x + i * (radius * 2 + space), y, radius, 0, (i + 1) * (2 * Math.PI) / arcCount, false);
ctx.stroke();
}
}
Code language: JavaScript (javascript)
出力

まとめ
- JavaScriptの
arc()
メソッドを使用して円弧を描画します。 - 新しい円弧を開始するには
beginPath()
メソッドを使用します。そして、stroke()
メソッドおよび/またはfill()
メソッドを使用して、円弧にストロークと塗りつぶしを適用します。