简体   繁体   English

如何在 canvas 中添加图像?

[英]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但不起作用

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).下面的代码片段首先加载图像(通过创建一个 promise 来解决image.onload完成)。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM