为什么不在加载时显示图像,而是在刷新时显示? [英] Why doesn't image show on load, but shows on refresh?
问题描述
我在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);
};
这篇关于为什么不在加载时显示图像,而是在刷新时显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!