LoginSignup
0
0

More than 3 years have passed since last update.

【入門者向け】Canvas入門講座#6 五角形を塗りつぶそう【JavaScript】

Posted at

問題6

点(100, 100)、(300, 200)、(250, 250)、(170, 280)、(50,150)を結ぶ五角形を塗りつぶしなさい。
塗りつぶす色は緑色(#00ff00)であること。
なお、以下のHTMLを使うこと。

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

    // 塗りつぶしの色を緑色にする
    ctx.fillStyle = '#00ff00';

    ctx.beginPath();        // 現在のパスをリセットする
    ctx.moveTo(100, 100);   // パスの開始座標を指定する
    ctx.lineTo(300, 200);   // 座標を指定してラインを引く
    ctx.lineTo(250, 250);   // 座標を指定してラインを引く
    ctx.lineTo(170, 280);   // 座標を指定してラインを引く
    ctx.lineTo(50, 150);    // 座標を指定してラインを引く
    ctx.closePath();        // パスを閉じる
    ctx.fill();           // 現在のパスを塗りつぶす
});
</script>
</head>
<body>
<canvas id="my-canvas" width="500" height="300"></canvas>
</body>
</html>

五角形が緑色で塗りつぶせました!
ダウンロード (7).png

解説

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

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

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

// 塗りつぶしの色を緑色にする
ctx.strokeStyle = '#00ff00';

後はパスを作成し、最後にfillを呼びます。

ctx.beginPath();        // 現在のパスをリセットする
ctx.moveTo(100, 100);   // パスの開始座標を指定する
ctx.lineTo(300, 200);   // 座標を指定してラインを引く
ctx.lineTo(250, 250);   // 座標を指定してラインを引く
ctx.lineTo(170, 280);   // 座標を指定してラインを引く
ctx.lineTo(50, 150);    // 座標を指定してラインを引く
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