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

324
Views
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 answers
Answer question

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 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!