Image Preloading in Canvas

我与影子孤独终老i 提交于 2020-01-24 20:56:25

问题


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(); // Create new Image object
img.src = 'test.php?filename=myfile.jpg'

and then

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

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.


回答1:


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';

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

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!');
};


来源:https://stackoverflow.com/questions/2921743/image-preloading-in-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!