繁体   English   中英

JS - Canvas图像在chrome中运行不正常(或者如何等待图像正确加载)

[英]JS - Canvas Image in not working well in chrome ( or how to wait for an image to load properly )

我有一个脚本在画布上绘制带有图像的QR码。

它正在使用一个插件,通常 - 一切都很好 - 但不是在chrome中。

HTML

<img id="#o99-qrs-img-buffer" src="http://localhost/www.beta.com/logo1.png" 
    style="display:none">
<div id="o99_qrcode" class="code"></div>

JS脚本如下(忽略PHP部分 - 它工作得很好):

 jQuery(document).ready(function() {

    var options = {
        render: "'.$qr_render.'", // Canvas, Div ,Image 
        size: '.$qr_size.',
        radius: '.  ($qr_corner_r * 0.1) .',

        .... tons of other options....

        // Image Label -> the problem is here 
        image: jQuery("#o99-qrs-img-buffer")[0], // taken as example
    };

    jQuery("#o99_qrcode").empty().qrcode(options);
});

如上所述,它在所有经过测试的浏览器上运行良好 - 除了在chrome中 - 它偶尔可以工作。 失败多于工作。 (90% - 10%)

稍微观察一下,我注意到两件事:

1 - jQuery(document).ready(function()并没有真正起作用我对它应该做什么的理解(当然我的理解可能是错误的)因为脚本在文档发出之前触发并显示图像完成加载。

2 - 我假设通过观察脚本失败了(与1相关) - 当脚本触发时,图像实际上无处可寻 - 所以它无处可去。

在开始时我责怪"display:none"并将div更改为style="width:100px;height:100px;" jQuery("#o99-qrs-img-buffer").hide(); 剧本解雇后。

不好 。

然后我尝试将jQuery(document).ready更改为loadonLoad

仍然没有去。

在SE上阅读了很多相关的问题 - 我发现了3个问题: 这里这里这里

所以我尝试实现第一个,看起来像一个可靠的解决方案:

var imagetest = new Image();

imagetest.onload = function() { 
    // wrap the firing in a function only when the image loads
    jQuery("#o99_qrcode").empty().qrcode(options);
};
imagetest.src: jQuery("#o99-qrs-img-buffer")[0]; // taken as example

但铬似乎比我更持久......

要么我完全错误地实现解决方案(非常可能),要么我对JS不熟悉,我首先不了解问题。

使用插件的脚本似乎无关紧要,因为插件在所有浏览器上运行良好(有时也是chrome ...)

无论如何,我需要帮助在找到加载图像的方法并确保在脚本触发之前加载它...

当DOM完全加载时, $(document).ready()被触发。 实际上,这在解析器刚刚遇到</body> 这并不意味着页面已准备好/完全加载, iframe s或img等外部资源的内容可能仍在加载。 $(document).ready()仅保证您可以引用HTML中的所有元素。

如果要等到整个页面并且其所有资源都已完全加载,则需要使用$(window).load()

看起来像document永远不会触发load事件, $(document).onLoad()不存在。

暂无
暂无

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

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