jQuery图像加载在Safari中不起作用

时间:2018-06-11 10:25:15

标签: javascript jquery safari

以下代码用于设置img的属性,然后在img load上执行某些操作。

这在Chrome和FireFox中运行良好,但是img ..etc行在Safari中永远不会受到影响。为什么是这样?

$("<img/>").attr("src", "data:image/*; base64," + base64).on("load", (e) => {
        let img = e.currentTarget;
        context.scale(width / img.width,  height / img.height);
        context.drawImage(img, 0, 0);
        deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
    });

我尝试过safari的技术预览版,但无济于事。这发生在Mac和iPhone上。

编辑:

根据Cross-browser image onload event handling

我试过了,但无济于事:

var image = $('<img/>');
image.on('load', e => {
    let img = e.currentTarget;
    context.scale(width / img.width,  height / img.height);
    context.drawImage(img, 0, 0);
    deferred.resolve($('<img/>').attr('src', canvas.toDataURL()));
});
image.attr('src', 'data:image/*; base64,' + base64);

我也试过普通的javascript

var image = $('<img/>');
image.onload = function(e) {
    let img = e.currentTarget;
    context.scale(width / img.width,  height / img.height);
    context.drawImage(img, 0, 0);
    deferred.resolve($('<img/>').attr('src', canvas.toDataURL()));
};
image.src = "data:image/*; base64," + base64;

1 个答案:

答案 0 :(得分:1)

您的数据网址标题格式不正确:

参数的分隔符应为;,没有空格。

Chrome和Firefox在允许它方面很不错。

"data:image/*;base64," + base64应该有用。

var base64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=='

var willWork = new Image();
willWork.onerror = willWork.onload = e => console.log('without space', e.type);
willWork.src = "data:image/*;base64," + base64;

var willFail = new Image();
willFail.onerror = willFail.onload = e => console.log('with space', e.type);
willFail.src = "data:image/*; base64," + base64;

但请注意,尽管我不知道浏览器支持这一点,但通过设置正确的MIME而不是通配符image/*,您会更安全。