javascript 绘制到 HTML5 Canvas 的图像在首次加载时无法正确显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8346418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image drawn to HTML5 Canvas does not display correctly on first load
提问by Jarek
I'm following a tutorial on importing and displaying images on an HTML5 canvas. Everything works fine, until I try to change the image itself. For example, I'll have a yellow circle as my image, and the script works fine. But if I open the image itself in Paint and change the circle to red, and refresh the page, the circle won't show up until I click or refresh again a second time manually. Here is the code snippet I'm using:
我正在学习有关在 HTML5 画布上导入和显示图像的教程。一切正常,直到我尝试更改图像本身。例如,我将有一个黄色圆圈作为我的图像,并且脚本运行良好。但是,如果我在 Paint 中打开图像本身并将圆圈更改为红色,然后刷新页面,则在我再次手动单击或再次刷新之前,圆圈不会显示。这是我正在使用的代码片段:
var topMap = new Image();
topMap.src = "topMap.png";
function drawMap() {
context.clearRect(0, 0, WIDTH, HEIGHT);
context.drawImage(topMap, 0, 0);
}
function init() {
drawMap();
}
init();
回答by Simon Sarris
The circle is probably not showing up because you are drawing it before the image is loaded. Change your last statement to:
圆圈可能没有显示出来,因为您在加载图像之前正在绘制它。将您的最后一条语句更改为:
// Lets not init until the image is actually done loading
topMap.onload = function() {
init();
}
The reason it works after you hit refresh is because the image is now pre-loaded into the cache.
点击刷新后它工作的原因是因为图像现在已预加载到缓存中。
You always want to wait for any images to load before you attempt to draw them or nothing will show up on the canvas instead.
在尝试绘制图像之前,您总是希望等待任何图像加载完毕,否则画布上将不会显示任何内容。