Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas toDataURL() returns blank image in Firefox even with .onload and callbacks

I have a problem with toDataURL() function in FireFox

Imagine I have such base64 image:

var url = " data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMTkgMTE5Ij48Zz48Y2lyY2xlIGN4PSI1NyIgY3k9IjYyIiByPSI1NyIgc3R5bGU9ImZpbGw6IHJnYigxNjAsIDE2MSwgMTYzKTsgb3BhY2l0eTogMC42OyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjU3IiBzdHlsZT0iZmlsbDogcmdiKDEyMywgMjEwLCAyNDApOyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjQ1IiBzdHlsZT0iZmlsbDogcmdiKDI1NSwgMjU1LCAyNTUpOyIvPjx0ZXh0IGR4PSI1NyIgZHk9IjY1IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBzdHlsZT0iZm9udC1zaXplOjI1cHg7IGZpbGw6ICMyYjJmMmU7IGZvbnQtZmFtaWx5OiAnRElOUHJvIFJlZ3VsYXInLCBzYW5zLXNlcmlmOyBmb250LXdlaWdodDogYm9sZCI+MTUlPC90ZXh0PjwvZz48L3N2Zz4=";

And then I want to resize it and send new uri back:

function getImageUri(url, callback) {
  image = new Image();

  image.onload = function() {
    var image = this; 
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        dataURL;

    context.drawImage(image, 0, 0, 60, 60);
    callback(canvas.toDataURL());
  }

  image.src = url;

}

At the end I just call it to get new uri

getImageUri(url, function (uri) {
    console.log(uri);
    document.getElementById('circle').innerHTML = "<img src=" + uri + ">";
});

Here is the codepen of this example. It works in Chrome, but not in FireFox.

I've searched a lot for similar questions here and most of time the reason was use of image without waiting for its loading, but I have this .onload thing, right?

And also I've tried to make same actions as in this question, but FF is still showing just transparent image. Please help!

like image 624
Paradoxetion Avatar asked Dec 23 '22 19:12

Paradoxetion


1 Answers

There’s a bug open in Firefox about this: drawImage() fails silently when drawing an SVG image without @width or @height.

You can fix it by adding (go figure) width and height to the SVG:

<svg
    xmlns="http://www.w3.org/2000/svg"
    width="119" height="119" viewBox="0 0 119 119">
    …

Updated Codepen

like image 101
Ry- Avatar answered Dec 31 '22 12:12

Ry-