javascript canvasタグに円形のグリッドを作成する

javascript canvasタグに円形のグリッドを作成する

javascriptで、canvasタグを使って、円形のグリッドを作成するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

円形のグリッドを作成

円形のグリッドを作成するには「for文」で、小さい円を色を変更しながら作成します。

<canvas id="cvs"></canvas>

<script>

// 2D図形を扱う
const ctx = cvs.getContext('2d');

const count = 6;

for (let i = 0; i < count; i++) {
  for (let j = 0; j < count; j++) {
  //~~はMath.floorの代わり
    ctx.strokeStyle = `rgb(${~~(255 - 51 * i)}, 0, ${~~(255 - 51 * j)})`;
    ctx.beginPath();
    ctx.arc(15 + j * 30, 15 + i * 30, 8, 0, Math.PI * 2, true);
  ctx.closePath();
    ctx.stroke();
  }
}

</script>

実行結果

サンプルコード

以下は、
「作成」ボタンをクリックすると、canvasタグにランダムな配色の30個の円形を作成する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数は、アロー関数で記述してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  const hoge = () => {

    // 2D図形を扱う
    const ctx = cvs.getContext('2d');

    const count = 6;

    for (let i = 0; i < count; i++) {
      for (let j = 0; j < count; j++) {
        //~~はMath.floorの代わり
        ctx.strokeStyle = `rgb(${~~(255 - Math.random() * 255)}, ${~~(255 - Math.random() * 255)}, ${~~(255 - Math.random() * 255)})`;
        ctx.beginPath();
        ctx.arc(15 + j * 30, 15 + i * 30, 8, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.stroke();
      }
    }

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main">

    <canvas id="cvs"></canvas>

    <button id="btn" type="button" class="btn btn-info">
      作成
    </button>

  </div>
</body>

</html>

ランダムな配色の30個の円が作成されていることが確認できます。