26

我有个问题。我正在尝试将图像绘制到画布上。图像不是来自 HTML 页面,而是来自文件。这是我使用的代码:

var img = new Image();
img.src = "/images/logo.jpg";
this._canvas.drawImage(img, 300, 300);// this is line 14

现在,问题来了。这似乎不适用于 Firefox 和 IE10(我还没有在其他浏览器上测试过)。在 Firefox (21) 上,我得到:

[19:09:02.976] NS_ERROR_NOT_AVAILABLE: Component is not available @ file:///D:/Watermellon/scripts/base-classes.js:14

在 IE10 上我得到:

SCRIPT16389: Unspecified error. 
base-classes.js, line 14 character 13

这些文件及其目录是:

root/index.html  
root/scripts/base-classes.js  
root/images/logo.jpg 

现在,当我将 img.src 更改为 URL(来自另一个站点的图像)时,一切正常,图像会在延迟后自行绘制(因为它是从 url 获取的)。我究竟做错了什么?

4

3 回答 3

28

我猜问题是在您尝试使用图像之前尚未加载图像。尝试这个:

var img = new Image();
img.onload = function () {
    this._canvas.drawImage(img, 300, 300);// this is line 14
};
img.src = "images/logo.jpg";

src属性是绑定事件后设置的,因为缓存图像的load事件会立即触发(这是 IE 中的常见问题)。

根据您的结构,图像的路径可能是images/logo.jpg(删除第一个/

于 2013-06-11T16:29:44.873 回答
5

在尝试将其绘制到画布中之前,您需要等待图像加载:

var img = new Image();
img.src = "/images/logo.jpg";
img.onload = function () {
  this._canvas.drawImage(img, 300, 300);// this is line 14
}
于 2013-06-11T16:29:31.373 回答
0

我在这里猜想的问题是资源何时可用?但是有一种方法可以确认资源可用,只需检查图像对象的“完整”属性即可。

if (img.complete == true){
   // is available.
} else {
   // wait until is ready.
}

此外,您可以使用 onload 事件和延迟方法创建一个合并方法来检查这两个东西。

var img = new Image();
//first attach handler
img.onload = function(e){
   if (e.target.complete == true) {
            yourHandler(e);
        } else {               
            var maxTimes = 10;
            var countTimes = 0;
            function retryLoadImage() {
                setTimeout(function () {
                    if (countTimes > maxTimes) {
                        // -- cannot load image.
                        return;
                    } else {
                        if (e.target.complete == true) {
                            yourHandler(e);
                        } else {
                            retryLoadImage();
                        }
                    }
                    countTimes++;
                }, 50);
            }; 
        }
};
img.src = yourSource;

这对我有用!!!在 IE 和 FF 上。

于 2015-03-03T18:17:18.393 回答