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
CodePudding user response:
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>