How to catch svg image fail to load in D3?

爱⌒轻易说出口 提交于 2019-12-01 06:44:20

This is more a JavaScript question then d3.js:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  <svg width="100" height="100"></svg>
  <script>
    
    // set up svg image tag
    var images = d3.select("svg")
      .append('svg:image')
      .attr('width', 50)
      .attr('height', 50);

    // create a test image
    var imgTest = new Image();
    // if it loads successfully add it to the svg image
    imgTest.onload = function() {
      images.attr("xlink:href", imgTest.src);
    }
    // if it fails test another image
    imgTest.onerror = function() {
      imgTest.src = "https://dummyimage.com/50x50/000/fff.png&text=An+Image!"
    }
    // this will fail
    imgTest.src = "https://does.not/exist.png";

  </script>

</body>

</html>

I know it's an old post but i found a simpler solution than Mark answer. So i post it for future users with the same issue.

In d3.js you can add events listeners on nodes (click, load, error, ...). So when the image fails to load you can change the link (with setAttribute() function) to a fallback image. Here is a working example (note that you should not add xlink: before href ):

var images = imageGroup.append('svg:image')
    .attr("href", function(d){
        return "ThisImageWillFailsToLoad.jpg"
    })
    .on("error", function(d){
        this.setAttribute("href", "YourFallbackImage.jpg");
    })
var images= imageGroup.append('svg:image')
  .attr("xlink:href",function(d,i){
    return "/img/" + filename + ".jpg"
  })
  // execute the callback function if the image fails to load
  .on('error', function(d) {
    // specify a default path for the image
    d3.select(this).attr("xlink:href", "/defaultPath");
  });
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!