JavaScriptでCanvas内にdrawImageした画像をrepeatする

まず結論から。以下のコードで画像の繰り返しが出きた。

HTML側はcanvasを用意してid=bgの画像を非表示で1個用意。

<body onload="xyz()">
  <canvas id="aaa" width="500" height="500"></canvas>
  <img id="bg" src="https://pg-happy.jp/wp-content/uploads/2022/06/btn-spin1.png" style="display:none;">
</body>

JavaScript側は以下のようにした。drawImageを使ってない。。

function xyz(){
  var canvas, ctx;
  var canvasBackgroundImg, repeatPtn;

  canvas = document.getElementById("aaa");
  ctx = canvas.getContext("2d");

  canvasBackgroundImg = document.getElementById("bg");
  repeatPtn = ctx.createPattern(canvasBackgroundImg, 'repeat');
  ctx.fillStyle = repeatPtn;
  ctx.fillRect(0,0,canvas.width, canvas.height);
  //ctx.drawImage(canvasBackgroundImg, 0,0);  
}

全体像はこちら。

See the Pen
img-click-event-test5
by pghappy (@pghappy)
on CodePen.

タイトルとURLをコピーしました