How to catch svg image fail to load in D3?

2019-02-26 02:18发布

问题:

I am using D3 to create a visualization with rows of <image> svg elements.

Could anyone know how I can upload a replacement image if the image file is not available?

    var images= imageGroup.append('svg:image')
           .attr("xlink:href",function(d,i){
                       //lines of code to process filename
                 return "/img/" + filename + ".jpg"

           })

回答1:

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>



标签: image d3.js load