Varsh
Varsh

Reputation: 465

How to fill html5 canvas grid squares with image?

I am new to html5 canvas. I want to draw one canvas grid and fill each grid square with an image from an API response. I have following code to draw the grid but I am struggling to fill each square with image. This is js code:

window.onload = function(){
    var c= document.getElementById('canvas');
    var ctx=c.getContext('2d');
    ctx.strokeStyle='white';
    ctx.linWidth=4;
    for(i=0;i<=600;i=i+60)
    {
      ctx.moveTo(i,0);
      ctx.lineTo(i,600);
      ctx.stroke();
    }

    for(j=0; j<=600; j=j+60)
    {
        ctx.moveTo(0,j);
        ctx.lineTo(600,j);
        ctx.stroke();
    }
}

This code helps me drawing canvas grid but how to access each square and fill it with the image. I referred links related to this but seems difficult to understand. Can somebody please help me with this?

Upvotes: 0

Views: 3168

Answers (1)

Rocky Sims
Rocky Sims

Reputation: 3598

It's hard to answer your question without knowing exactly how the image is being returned by the api response. Assuming the api response is returning the image itself (not the image data in JSON or something like that) here is a solution:

html:

<canvas id="canvas" width="600" height="600"></canvas>

javascript:

window.onload = function() {
  const canvas = document.getElementById("canvas");
  const ctx = canvas.getContext("2d");
  ctx.strokeStyle = "green";
  ctx.lineWidth = 4;

  //draw grid
  for (let i = 0; i <= 10; i++) {
    const x = i*60;
    ctx.moveTo(x, 0);
    ctx.lineTo(x, canvas.height);
    ctx.stroke();

    const y = i*60;
    ctx.moveTo(0, y);
    ctx.lineTo(canvas.width, y);
    ctx.stroke();
  }

  //draw images
  const p = ctx.lineWidth / 2; //padding
  for (let xCell = 0; xCell < 10; xCell++) {
    for (let yCell = 0; yCell < 10; yCell++) {
      const x = xCell * 60;
      const y = yCell * 60;
      const img = new Image();
      img.onload = function() {
        ctx.drawImage(img, x+p, y+p, 60-p*2, 60-p*2);
      };

      //TODO: set img.src to your api url instead of the dummyimage url.
      img.src = `https://dummyimage.com/60x60/000/fff&text=${xCell},${yCell}`;
    }
  }
};

Working example:

https://codepen.io/rockysims/pen/dLZgBm

Upvotes: 3

Related Questions