Alternate/Fallback 使用 Snap SVG 时的图像

Alternate/Fallback Image while using Snap SVG

我刚刚下载了 Snap SVG,我正在尝试弄清楚如何显示具有回退排列的图像。这是代码:

var s = Snap("#MyPopup");
var g = s.g();
var image = g.image("http://myimages.com/xyz.png", 250, 10, 40,40 );

这样可以完美显示图像。但是,如果图像丢失,则会出现损坏的图像不喜欢的图标。相反,我想显示备用图像,比如 http://myimages.com/abc.png ,如果找不到主图像(类似于与 <img> 一起使用的 onerror)。有人可以指导我怎么做吗?

根据@AustinC 的提示,我稍微修改了他建议的 Check if image exists on server using JavaScript? 中给出的解决方案。

基本上建议的功能是 returning 403(而不是 404),因为我的图像托管在亚马逊云上,因此我选择检查 return 代码 200(确定)。这是最终的解决方案。

var s = Snap("#MyPopup");
var image = null;
var mImagePath = "https://myimages.com/xyz.png";

if ( imageExists (mImagePath) == true ) {
    image = s.image(mImagePath, 250, 10, 40,40 );                   
} else {
    image = s.image("https://myimages.com/ImageNotFound.png", 250, 10, 40,40 );
}


function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status == 200;

}