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);
};
这篇关于为什么图像在加载时不显示,但在刷新时显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么图像在加载时不显示,但在刷新时显示?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01