为什么图像在加载时不显示,但在刷新时显示?

2022-01-17 00:00:00 javascript html html5-canvas

我正在使用 HTML5 中的 canvas 元素,我注意到一种特殊的行为.在初始加载时,我正在显示的图像不显示.但是,当我刷新浏览器时,它会正确显示.我用过 IE9 和 Chrome.两者的行为相同.JavaScript 代码如下所示:

I'm playing with the canvas element in HTML5 and I have noticed a peculiar behavior. On initial load, an image I'm displaying does not show. However, when I refresh the browser, it displays appropriately. I've used IE9 and Chrome. Both behave identically. The JavaScript code looks like this:

window.onload = load;
function load() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    context.fillRect(0, 0, 640, 400);
    var image = new Image();
    image.src = "Images/smiley.png";
    context.drawImage(image, 50, 50);
}

矩形两次都正确绘制,它是只在浏览器刷新时显示的笑脸.

The rectangle draws correctly both times, it's the smiley that only shows on a browser refresh.

我正在学习 HTML5 和 JavaScript.我确定我只是在做一些愚蠢的事情,但我无法弄清楚.

I'm in the process of learning HTML5 and JavaScript. I'm sure I'm just doing something stupid, but I can't figure it out.

推荐答案

图片是异步加载的,所以只有在刷新后才加载足够早,因为它是缓存的.通常在您调用 drawImage 时它还没有加载.使用onload:

Images load asynchronously, so only after refresh it loads early enough because it's cached. Normally it isn't loaded yet at the time you call drawImage. Use onload:

var image = new Image();
image.src = "Images/smiley.png";
image.onload = function() {
    context.drawImage(image, 50, 50);
};

相关文章