簡體   English   中英

如何用圖像填充html5畫布網格正方形?

[英]How to fill html5 canvas grid squares with image?

我是html5 canvas的新手。 我想繪制一個畫布網格,並用API響應中的圖像填充每個網格正方形。 我有以下代碼來繪制網格,但是我正在努力用圖像填充每個正方形。 這是js代碼:

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();
    }
}

此代碼可幫助我繪制畫布網格,但如何訪問每個正方形並用圖像填充它。 我提到了與此相關的鏈接,但似乎很難理解。 有人可以幫我嗎?

如果不確切知道api響應如何返回圖像,很難回答您的問題。 假設api響應返回的是圖像本身(而不是JSON中的圖像數據或類似的圖像),這是一個解決方案:

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}`;
    }
  }
};

工作示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM