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

325
Vistas
How put over the dot a image, in a canvas?

How can i put image in each of objects?

currently only its showing dots, but i need show image

for (var i = 0; i < objects.length; i++) {
        var object = objects[i];
        object.y += spawnRateOfDescent;
        ctx.beginPath();
        ctx.arc(object.x, object.y, 8, 0, Math.PI * 2);


       


        ctx.closePath();
        ctx.fillStyle = object.type;
        ctx.fill();
    }

I tried with this

var img = new Image();
    img.src = "img/HannyahNED/Cohete_1"+".png";
    img.onload = function () {
        ctx.drawImage(img, object.x, object.y);
    };

but does not worked

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The key idea is that loading images is asynchronous. The snippet below loads images first (by creating a promise that resolves when image.onload completes).

After that, your code works fine.

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

const objects = [{
    x: 10,
    y: 10,
    src: "https://via.placeholder.com/60/FF0000" // red image
  },
  {
    x: 90,
    y: 90,
    src: "https://via.placeholder.com/60/00FF00" // green image
  },
  {
    x: 170,
    y: 170,
    src: "https://via.placeholder.com/60/0000FF" // blue image
  }
]

function fetchImage(url) {
  return new Promise(resolve => {
    const img = new Image();
    img.src = url;
    img.onload = () => resolve(img);
  });
}

const promises = objects.map(object => {
  return fetchImage(object.src).then(img => object.img = img)
});

Promise.all(promises).then(() => {
  objects.forEach(object => {
    ctx.drawImage(object.img, object.x, object.y);
    ctx.beginPath();
    ctx.arc(object.x, object.y, 8, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
  });
})
<div>
  <canvas width="400" height="400"></canvas>
</div>

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