简体   繁体   English

如何强制加载未在 HTML5 canvas 中加载的图像?

[英]How to force load an image which is not loading in HTML5 canvas?

let head = new Image();
head.src = "img/head.png";

if(!head.complete)
    console.log('NOT');

In the code above I am getting NOT in my log for the first time the page loads and then when I refresh the page nothing is logged as the image loads.在上面的代码中,我第一次加载页面时没有出现在我的日志中,然后当我刷新页面时,在加载图像时没有记录任何内容。 How to force load the image in first page load?如何在第一页加载时强制加载图像?

I have referred to many answers on SO but nothing has helped till now.我已经提到了很多关于 SO 的答案,但到目前为止没有任何帮助。 I used onload but the image is just not loading on the first load as I checked it using head.complete .我使用了onload但图像只是没有在第一次加载时加载,因为我使用head.complete检查它。 I even added a timestamp at the end of the image "head.png?"+getTime(new Date()) if there was a problem regarding caching.. But no luck!如果缓存有问题,我什至在图像"head.png?"+getTime(new Date())的末尾添加了一个时间戳。但没有运气!

And all other images are loading perfectly.并且所有其他图像都可以完美加载。

Im assuming that your script is running directly in the top level function document.ready(), or your script is inside a function that is running inside the first one.我假设您的脚本直接在顶级 function document.ready() 中运行,或者您的脚本在第一个内部运行的 function 中。 then you may check one of this one:那么您可以检查以下之一:

The image is considered completely loaded if any of the following are true:如果满足以下任一条件,则认为图像已完全加载:

Neither the src nor the srcset attribute is specified. src 和 srcset 属性均未指定。 The srcset attribute is absent and the src attribute, while specified, is the empty string (""). srcset 属性不存在,并且 src 属性在指定时是空字符串 ("")。 The image resource has been fully fetched and has been queued for rendering/compositing.图像资源已完全提取并已排队等待渲染/合成。 The image element has previously determined that the image is fully available and ready for use.图像元素先前已确定该图像完全可用并且可以使用。 The image is "broken;"图像“破碎”; that is, the image failed to load due to an error or because image loading is disabled.也就是说,由于错误或图像加载被禁用,图像无法加载。 It's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running.值得注意的是,由于图像可能是异步接收的,所以在脚本运行时完成的值可能会发生变化。

Also Im assuming that you appended the head variable to the or body element.另外我假设您将 head 变量附加到 or body 元素。 You can check to in the browser console if the link to the image is ok (if you step over the link, it will show the image)如果图像链接正常,您可以在浏览器控制台中检查(如果您跳过链接,它将显示图像)

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

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