javascript canvasで画像を繰り返して表示する

javascript canvasで画像を繰り返して表示する

javascriptで、canvasタグを使用して、画像を回転させて表示するサンプルコードを記述してます。

環境

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

canvasタグ使い方

rotateを使用すれば、画像を回転させて表示することが可能です。

<canvas id="cvs" width="500" height="500"></canvas>

<script>

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

// Image オブジェクトを生成
const img = new Image; // ()を省略

// 画像を表示
img.src = '150x150.png';

// 画像読み込み完了後に描画
img.onload = () => {
  // drawImage(画像, x座標, y座標)
  ctx.drawImage(img, 300, 0);
  // 回転
  ctx.rotate(30 * Math.PI / 180);

}

</script>

サンプルコード

以下は、
「実行」ボタンをクリックすると、画像を回転させて表示していく
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。

<!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>

  function hoge() {

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

    // Image オブジェクトを生成
    const img = new Image; // ()を省略
    // 画像を表示
    img.src = '150x150.png';

    // 画像読み込み完了後に描画
    img.onload = () => {
      // drawImage(画像, x座標, y座標)
      ctx.drawImage(img, 300, 0);
      // 回転
      ctx.rotate(30 * Math.PI / 180);

    }

  }

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

</script>

<body>
  <div class="main">

    <canvas id="cvs" width="500" height="500"></canvas>

    <button id="btn" type="button" class="btn btn-info">
      実行
    </button>

  </div>
</body>

</html>

画像が回転されて表示されていることが確認できます。