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

  • URLをコピーしました!
まず結論から。以下のコードで画像の繰り返しが出きた。 HTML側はcanvasを用意してid=bgの画像を非表示で1個用意。
<body onload="xyz()">
  <canvas id="aaa" width="500" height="500"></canvas>
  <img id="bg" src="http://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.


目次

プログラミング学習を体系的に進めたい人へ

独学で基礎を確認したあとに、質問できる環境や転職・副業向けの学習サポートも比べたい人は、プログラミングスクールの比較記事も参考にしてください。学習目的、料金、受講期間、サポート範囲を分けて見ると、自分に合う学び方を選びやすくなります。


目次