1

I am looping and combining images, but I simply get a blank canvas. Here is my code:

    const canvas = createCanvas(1024, 1024);
    const numberOfSquares = Math.sqrt(imageFiles.length);
    const size = 1024 / numberOfSquares;

    var currentX = 0;
    var currentY = 0;

    for (let h = 0; h < numberOfSquares; h++) {
      for (let i = 0; i < numberOfSquares; i++) {
        loadImage('./images/0.png').then((image) => {
          ctx.drawImage(image, currentX, currentY, size, size);
          currentX += size;
        });

        if (h === 9 && i === 9) {
          console.log(canvas.toDataURL());
          // hardcoded value for testing
        }

        currentX += size;
      }
      currentX = 0;
      currentY += size;
    }

There are two problems

  1. The canavas gets logged before the loop has completed
  2. When I log currentX and currentY I simply get
102.4 1023.9999999999999
204.8 1023.9999999999999
307.20000000000005 1023.9999999999999
409.6 1023.9999999999999
512 1023.9999999999999
614.4 1023.9999999999999
716.8 1023.9999999999999
819.1999999999999 1023.9999999999999
...

Note: when I test it with stroke, beginPath, rect etc it works fine

EDIT

See comments for answer

Here's the updated code btw

const canvas = createCanvas(1024, 1024);
    const numberOfSquares = Math.sqrt(imageFiles.length);
    const size = 1024 / numberOfSquares;

    var currentX = 0;
    var currentY = 0;

    for (let h = 0; h < numberOfSquares; h++) {
      for (let i = 0; i < numberOfSquares; i++) {
        const image = await loadImage('./images/0.png');
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, currentX, currentY, size, size);
        currentX += size;

        if (h === 9 && i === 9) {
          console.log(canvas.toDataURL());
        }
      }
      currentX = 0;
      currentY += size;
Arya Anish
  • 85
  • 2
  • 9
  • 1
    `loadImage` is async, the callback in the `.then()` will only be called later on, so when you reach the `if (h === 9 && i === 9) {` step, even the first image still hasn't been drawn on the canvas. Convert your code to be inside an ` async` function (depending on your node's version you may already have global async), then in your lood instead of doing `loadImage(...).then(callback)` do `await loadImage(...); ctx.drawImage(...); currentX += ...`. – Kaiido Jan 31 '22 at 06:52

0 Answers0