简体   繁体   中英

How to make Canvas wait for image to load

I am loading an image through my REST API to my frontend. 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. 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. Try setting the canvas dimensions to the images dimensions in the onload handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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