绘制到 HTML5 Canvas 的图像在首次加载时无法正确显示 [英] Image drawn to HTML5 Canvas does not display correctly on first load

查看:94
本文介绍了绘制到 HTML5 Canvas 的图像在首次加载时无法正确显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习有关在 HTML5 画布上导入和显示图像的教程.一切正常,直到我尝试更改图像本身.例如,我将有一个黄色圆圈作为我的图像,并且脚本运行良好.但是,如果我在 Paint 中打开图像本身并将圆圈更改为红色,然后刷新页面,则在我再次手动单击或再次刷新之前,圆圈不会显示.这是我正在使用的代码片段:

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:

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.

这篇关于绘制到 HTML5 Canvas 的图像在首次加载时无法正确显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆