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

147
Views
getImageData/putImageData not drawing expected output

I have this variable that saves the previous state of the canvas through getImageData(), however when I draw over it then try to revert back to the old state with putImageData() it doesn't work:

window.onload = async () => {
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  let map;

  const drawPicture = async (image) => {
    const img = new Image();

    img.src = `assets/${image}.png`;
    img.onload = () => {
      ctx.drawImage(img, 0, 0, 60, 60);
    }
  }

  await drawPicture('log');
  map = ctx.getImageData(0, 0, 60, 60);
  await drawPicture('box');
  await ctx.putImageData(map, 0, 0);
}

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The culprit is the onload handler inside the drawPicture function. Simply marking a function as async using the async prefix isn't enough. In your case the function should wait until the image is loaded and draw it onto the canvas right after.

Written as it is right now, the onload handlers would fire sometime after your last function call :

await ctx.putImageData(map, 0, 0);

So the proper way is to let the function return a Promise, which is fulfilled as soon as the onload handler fires.

window.onload = async () => {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    let map;

    const drawPicture = async (image) => {
        return new Promise(resolve => {
            const img = new Image();
            img.onload = () => {
                ctx.drawImage(img, 0, 0, 60, 60);
                resolve();
            }
            img.src = `assets/${image}.png`;
        });
    }

    await drawPicture('a');
    map = ctx.getImageData(0, 0, 60, 60);
    await drawPicture('b');
    await ctx.putImageData(map, 0, 0);
}
about 4 years ago · Juan Pablo Isaza Report
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!