LoginSignup
0
0

More than 3 years have passed since last update.

【入門者向け】Canvas入門講座#8 円を塗りつぶそう【JavaScript】

Posted at

問題8

中心が(200, 200)、半径100の円を塗りつぶしなさい。
塗りつぶす色はマゼンタ色(#ff00ff)であること。
なお、以下のHTMLを使うこと。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>問題8</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(() => {
    // ここにプログラムを書く
});
</script>
</head>
<body>
<canvas id="my-canvas" width="500" height="300"></canvas>
</body>
</html>

答え

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>問題8</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(() => {
    // コンテキストを取得
    const ctx = $('#my-canvas')[0].getContext('2d');

    // 塗りつぶしの色をマゼンタ色にする
    ctx.fillStyle = '#ff00ff';

    ctx.beginPath();        // 現在のパスをリセットする
    ctx.arc(200, 200, 100, 0, Math.PI*2, true); // 円を描画する
    ctx.closePath();        // パスを閉じる
    ctx.fill();           // 現在のパスを塗りつぶす
});
</script>
</head>
<body>
<canvas id="my-canvas" width="500" height="300"></canvas>
</body>
</html>

円が塗りつぶせました!
image.png

解説

コンテキストを取得します。これは問題1と同じです。

// コンテキストを取得
const ctx = $('#my-canvas')[0].getContext('2d');

次に塗りつぶしの色を指定します。
塗りつぶしの色はfillStyleで指定します。

// 塗りつぶしの色をマゼンタ色にする
ctx.fillStyle = '#ff00ff';

後はパスを作成し、最後にfillを呼びます。
円弧の描画arcメソッドについては問題7の解説をご覧ください。

ctx.beginPath();        // 現在のパスをリセットする
ctx.arc(200, 200, 100, 0, Math.PI*2, true); // 円を描画する
ctx.closePath();        // パスを閉じる
ctx.fill();           // 現在のパスを塗りつぶす
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0