Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image onload not called when setting source

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/

like image 310
Bram Avatar asked Feb 05 '23 07:02

Bram


1 Answers

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>';
like image 157
mplungjan Avatar answered Feb 08 '23 11:02

mplungjan