duhaime
duhaime

Reputation: 27594

JavaScript: One Canvas Multiple Textures

I'm trying to render multiple images on a single canvas, but seem to be overlooking something:

var canvas = document.createElement('canvas');
canvas.width = 4086;
canvas.height = 4086;

var ctx = canvas.getContext('2d');
var loadedImages = 0;

for (var j=0; j<4; j++) {
  var url = 'https://via.placeholder.com/2048x2048';
  var img = new Image();
  img.onload = function(j) {
    var w = 2048;
    var h = 2048;
    var x = (j % 2) * w;
    var y = (Math.floor(j / 2)) * h;
    console.log(img, x, y, w, h)
    ctx.drawImage(img, x, y, w, h, x, y, w, h);
    if (++loadedImages == 4) {
      document.body.appendChild(canvas)
    }
  }.bind(null, j)
  img.src = url;
}
canvas {
  width: 500px;
}

Does anyone see what I'm missing? Any help others can offer would be greatly appreciated!

Upvotes: 0

Views: 29

Answers (1)

Pointy
Pointy

Reputation: 413712

You're using the long-form API to draw the image, which is designed to select a portion of your source image to draw onto the canvas. You really only need the "short" version, because (I think) you want to draw the entire image four times.

When you use the long form, the code is requesting pixels that don't exist in the source image because it's only 2048x2048 pixels in size.

Upvotes: 1

Related Questions