使用EaselJS位图时捕获错误的URL

Catch bad URLs when using EaselJS bitmap

本文关键字:错误 URL EaselJS 位图 使用      更新时间:2023-09-26

在尝试将URL加载到createjs之前,是否有方法检查URL是否导致有效的图像。位图?我一直试图捕捉错误的URL(在Firefox中),但由于某种原因,这不起作用。

    try {
        image = new createjs.Bitmap ( "image" );
    } catch ( err ) {
        console.log ( "oops" );
        return null;
    }

当我在Firefox中运行此代码时,错误仍然会显示在控制台中,并且记录的消息不会。那么,我的问题是,有没有一种方法可以预先验证URL?

如果图像是坏的、未定义的、null等,则不会throw出错,因此try/catch将不起任何作用。

如果使用PreloadJS(CreateJS套件的一部分)加载图像,则可以侦听error事件,如果任何图像加载失败(或超时),队列将抛出该事件。

var queue = new createjs.LoadQueue();
queue.on("error", handleError);
queue.loadFile("404image.png");

目前还没有内置的方法只使用原始Bitmap实例来确定是否发生错误。通过字符串路径传递到位图的图像不会被预加载,而只是使用Image实例在内部请求。

您可以使用普通JS来检测图像是否可以加载,如果可以,则将该实例传递给EaselJS Bitmap:

var img = new Image();
img.onload = function() {
    console.log('img loaded');
    var bitmap = new createjs.Bitmap(img);
}
img.onerror = function() {
    console.log('error');
} 
img.src = 'notexistingimage.png';