Image onload not called when setting source

自作多情 提交于 2021-01-27 07:10:59

问题


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/


回答1:


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



回答2:


Try adding the xmlns and version attributes to the svg.

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




回答3:


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;



回答4:


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.



来源:https://stackoverflow.com/questions/41739791/image-onload-not-called-when-setting-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!