Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda