1

The following code is used to set the attributes of an img and then do something upon img load.

This works fine in Chrome and FireFox, however the let img..etc line never gets hit in Safari. Why is this?

$("<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()));
    });

I've tried with the tech preview version of safari, to no avail. This occurs on Mac and iPhone.

Edit:

As per Cross-browser image onload event handling

I've tried, to no avail:

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

I've also tried with plain 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;
Wayneio
  • 3,466
  • 7
  • 42
  • 73
  • 1
    According to the [docs](https://api.jquery.com/load-event/) it doesn't work reliably across browsers. – H77 Jun 11 '18 at 10:26
  • Possible duplicate of [Cross-browser image onload event handling](https://stackoverflow.com/questions/10403983/cross-browser-image-onload-event-handling) – H77 Jun 11 '18 at 10:29
  • @H77 the docs don't give a safari alternative. Tried the option already in the post you linked – Wayneio Jun 11 '18 at 11:56

1 Answers1

1

Your data URL headers are not in a correct format:

The delimiter for parameters should be ;, without space.

Chrome and Firefox are being nice here in allowing it.

"data:image/*;base64," + base64 should work.

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;

But note that even though I have no idea of browser support for this, you would be even safer by setting the correct MIME instead of the wildcard image/*.

Kaiido
  • 123,334
  • 13
  • 219
  • 285