简体   繁体   English

绘制到HTML5 Canvas的图像在首次加载时无法正确显示

[英]Image drawn to HTML5 Canvas does not display correctly on first load

I'm following a tutorial on importing and displaying images on an HTML5 canvas. 我正在关注在HTML5画布上导入和显示图像的教程。 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. 但是如果我在Paint中打开图像本身并将圆圈更改为红色并刷新页面,则直到我再次手动点击或再次刷新时,圆圈才会显示。 Here is the code snippet I'm using: 这是我正在使用的代码片段:

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();

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. 您总是希望在尝试绘制图像之前等待加载任何图像,否则画布上不会显示任何图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM