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

Why doesn#39;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);
};

这篇关于为什么图像在加载时不显示,但在刷新时显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么图像在加载时不显示,但在刷新时显示?

基础教程推荐