user3562812
user3562812

Reputation: 1829

How to catch svg image fail to load in D3?

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"

           })

Upvotes: 7

Views: 1494

Answers (3)

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

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");
    })

Upvotes: 5

Delonix
Delonix

Reputation: 1

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");
  });

Upvotes: -1

Mark
Mark

Reputation: 108527

This is more a JavaScript question then d3.js:

<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" 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>

Upvotes: 3

Related Questions