Froxx Froxx - 24 days ago 8
Javascript Question

Simplest way to tile an Image in JS

I have a PNG graphic I want to use as a background for my canvas in JS. It should be displayed in a tiled format. For this I'm currently doing something like this.

const ratioX = Math.ceil(canvas.width / image.width);
const ratioY = Math.ceil(canvas.height / image.height);
for (var x = 0; x < ratioX; x++) {
for (var y = 0; y < ratioY; y++) {
ctx.drawImage(image, x*image.width, y*image.height, image.width, image.height);
}
}


It's working as intended, but the performance might get improved by not doing the calculations every frame, but buffering the bigger tiled version of my image. So I'm looking for a way to create this image as an instance of the
Image
class or any other class I can use for
drawImage()
.

At first I might need to get the image data (so the rgba info for every pixel). I've seen a way to do it like here, using canvas's context, but do I really need to do that? Is there no simpler way?

The second step would be to create a drawable image object out of that data. How would I do that?

I would love to see a way that's equivalent to Java's
bufferedImage.getRgb(x, y)
and
bufferedImage.setRgb(x, y, color)
. Does something like this exist in JS?

Answer

As shown here in W3Schools you can use ctx createPattern to achieve what you want:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var img = new Image();
img.src = 'http://placehold.it/50/50'
img.onload = function() {
  var pat = ctx.createPattern(img, 'repeat');
  ctx.rect(0, 0, 350, 350);
  ctx.fillStyle = pat;
  ctx.fill();
};
<canvas id='canvas' width=350 height=350/>