4

Why is the onload event never fired in following snippet?

var img = new Image()
img.onload = function() {
  alert("ok");
}
var svg = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>'

img.src = 'data:image/svg+xml;base64,'+ btoa(svg);

Link to jsfiddle: https://jsfiddle.net/venmmn3b/1/

Bram
  • 121
  • 1
  • 6

4 Answers4

5

Because it is NOT ok -

  • missing quote in your svg string
  • the image triggers the error and not the load handler

var img = new Image()
img.onload = function() {
  console.log("ok");
}
img.onerror = function(e) {
  console.log("Not ok",e);
}
var svg = '<svg></svg>';
img.src = 'data:image/svg+xml;base64,'+ btoa(svg);

I even tried to add valid svg:

var img = new Image()
img.onload = function() {
  console.log("ok");
}
img.onerror = function(e) {
  console.log("Not ok",e);
}
img.src = 'data:image/svg+xml;utf8,<svg><text font-size="68" font-weight="bold" font-family="DejaVu Sans" y="52" x="4" transform="scale(.8,1.7)"><tspan fill="#248">W3</tspan>C</text> <path fill="none" stroke="#490" stroke-width="12" d="m138 66 20 20 30-74"/></svg>';
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

Try adding the xmlns and version attributes to the svg.

Example: <svg version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>

Terje
  • 1,753
  • 10
  • 13
1

Thanks to Terje answer I managed to make it work. I still had to create a blob and an object URL as stated in this tutorial.

    // SVG Containing version and xmlns attributes as Terje stated
    const my_svg = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>`; 
    const img = document.createElement('img');

    const blob = new Blob([my_svg], { type: 'image/svg+xml;charset=utf-8' })
    const URLSrc = URL.createObjectURL(blob);

    img.onload = function () {
      console.log('Image Loaded')
    }

    img.src = URLSrc;
HenriC
  • 842
  • 8
  • 14
0

You are missing a quote in the line

 var svg = '<svg></svg>';.

and also it's working when i keep image source as "http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg". So i think there is something wrong with your image only.

Daga Arihant
  • 464
  • 4
  • 19