Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!