Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
loadImage not working while looping canvas node.js

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;
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda