简体   繁体   English

如何使Canvas等待图像加载

[英]How to make Canvas wait for image to load

I am loading an image through my REST API to my frontend. 我正在通过REST API将图像加载到前端。 Now I want to mark specific areas on the image with the help of coordinates. 现在,我想在坐标的帮助下标记图像上的特定区域。 The only idea I have had is to draw the image on a canvas and draw the marked areas on a higher level canvas. 我唯一的想法是在画布上绘制图像,并在更高级别的画布上绘制标记的区域。 Every time I load the picture it gets drawn on the canvas with a different smaller size. 每次加载图片时,它都会以不同的较小尺寸绘制在画布上。 I presume it has something to do with the canvas drawing before the image is fully loaded, but I havent figured out yet how to get it to work. 我认为它与图像完全加载之前的画布绘图有关,但是我还没有弄清楚如何使它起作用。

let canvas = document.getElementById('c');
let ctx = canvas.getContext('2d');
let canover = document.getElementById('cover');
let ctxover = canvas.getContext('2d');

let img = new Image();
img.onload = function () {
    ctx.drawImage(img, 0, 0);
    ctxover.fillRect(0,0,10,10);
    ctxover.fillRect(0,20,10,10);
    ctxover.fillRect(20,0,10,10);
    ctxover.fillRect(20,20,10,10);
}
canvas.width = img.width;
canvas.height = img.height;
canover.width = img.width;
canover.height = img.height;

I've looked at the img.height and img.width and they are often wrong. 我看过img.height和img.width,它们通常是错误的。 So I am looking for an easy way to only start the drawing after the image has fully loaded. 因此,我正在寻找一种仅在图像完全加载后才开始绘制的简单方法。 I've tried working with fetch to get the image and then to draw it, but I couldn't get it right. 我尝试使用获取来获取图像,然后绘制它,但是我做不正确。

You seem to be setting the canvas dimensions before the the onload handler has executed. 您似乎在执行onload处理程序之前设置了画布尺寸。 Try setting the canvas dimensions to the images dimensions in the onload handler. 尝试在onload处理程序中将画布尺寸设置为图像尺寸。

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

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