画布中的图像预加载 [英] Image Preloading in Canvas

查看:36
本文介绍了画布中的图像预加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用drawImage函数在画布上绘制图像.我就是这样设置图像的src属性的:

I'm drawing an Image on the canvas using the drawImage function. This is how Im setting the src property of the image:

var img = new Image();//创建新的Image对象
img.src ='test.php?filename = myfile.jpg'

var img = new Image(); // Create new Image object
img.src = 'test.php?filename=myfile.jpg'

然后

oCanvas.width = 600;oCanvas.height = 400;oContext.drawImage(img,0,0,600,400);

oCanvas.width = 600; oCanvas.height = 400; oContext.drawImage(img, 0, 0, 600, 400);

问题是,如果未设置src,则会收到以下错误:"未捕获的异常:[Exception ..."组件返回了失败代码:0x80040111(NS_ERROR_NOT_AVAILABLE)[nsIDOMCanvasRenderingContext2D.drawImage]",我知道我收到此错误,原因是图像尚未完成加载.我在调用drawImage函数之前添加了一个警报,以使图像完成加载,而且似乎可以正常工作,但这是一个痛苦的事情.我要检查图像是否已完成加载吗?顺便说一句,我必须通过调用php文件来设置src属性.

The problem is that if the src isn't set then I get the foll error:"uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]" . I know I get this error coz the image hasnt finished loading. I added an alert just before the call to drawImage function to let the image finish loading and it seems to work. But it's a pain in the neck. How do I check if the image has finished loading? BTW I have to set the src property by calling a php file.

推荐答案

在设置图像的 src 属性之前,先定义 .

Define this before you set the image's src attribute.

// Create new Image object
var img = new Image(); 

img.onload = function() {
    // add it to the canvas
    oCanvas.width = 600; oCanvas.height = 400;
    oContext.drawImage(img, 0, 0, 600, 400);
};

img.src = 'test.php?filename=myfile.jpg';

(必须先定义它,否则IE7不会将其触发).

(it needs to be defined first because otherwise IE7 will not fire it).

此外,如果您想对该错误进行处理,请使用JavaScript的 try/catch .

Also, if you wanted to do something with that error, use JavaScript's try/catch.

try {
    oCanvas.width = 600; oCanvas.height = 400;
    oContext.drawImage(img, 0, 0, 600, 400);
} catch (exception) {
    alert('something went wrong!');
};

这篇关于画布中的图像预加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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