Is it possible to listen image load event in SVG?

不打扰是莪最后的温柔 提交于 2019-12-04 17:53:09

问题


Is it possible to listen for an <image> load event in SVG? If yes, how to do this?


回答1:


Yes it's possible.

In markup:

<image xlink:href="example.png" width="10" height="10" 
       onload="alert('loaded')"/>

See jsfiddle.

In script:

<script>
  var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
  img.addEventListener('load', function() { alert('loaded'); });
  // or alternatively:
  // img.onload = function() { alert('loaded'); }
  img.width.baseVal.value = 100;
  img.height.baseVal.value = 100;
  img.href.baseVal = "example.png";
</script>

See jsfiddle.




回答2:


I found that this would not work for SVG object created using D3, but the answer here worked great:

How can I display a placeholder image in my SVG until the real image is loaded?

For example this worked:

var img = innerG.append("image")
    .attr('onload', function() {
        console.log('loaded');
    })
    .attr("xlink:href", src)
    .attr("width", size)
    .attr("height", size);

But this did not work:

var img = innerG.append("image")
    .attr("xlink:href", src)
    .attr("width", size)
    .attr("height", size);

img.addEventListener('load', function() { console.log('loaded'); });


来源:https://stackoverflow.com/questions/11390830/is-it-possible-to-listen-image-load-event-in-svg

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