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

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

问题描述

我正在关于在HTML5画布上导入和显示图像的教程。一切工作正常,直到我尝试改变图像本身。例如,我有一个黄色的圆圈作为我的形象,脚本工作正常。但如果我在油漆中打开图像本身并将圆形更改为红色,并刷新页面,该圆圈将不会显示,直到我再次单击或手动刷新第二次。这里是我使用的代码片段:

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天全站免登陆