Bram
Bram

Reputation: 121

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/

Upvotes: 4

Views: 5403

Answers (4)

mplungjan
mplungjan

Reputation: 177830

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

Upvotes: 5

HenriC
HenriC

Reputation: 912

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;

Upvotes: 1

Terje
Terje

Reputation: 1763

Try adding the xmlns and version attributes to the svg.

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

Upvotes: 2

Daga Arihant
Daga Arihant

Reputation: 484

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.

Upvotes: 0

Related Questions