1

i am appending svg images to chart.But sometime the image source may not exists. In order to avoid the situation, i have replace the un existing image with default one.

 g.selectAll("image")
 .data(data)
 .enter()
   .append("svg:image")
   .attr("xlink:href",function(d){
       return d.name+".jpg";
    })
   .attr("x", function (d,i) { return x(d.x); } )
   .attr("y", function (d,i) { return y(100); } )
   .attr("width",imageSize)
   .attr("height",imageSize);

suppose d.name+".jpg" not present in directory. I have to replace it by default.jpg.

how can i do that??

Thanks in advance.

Merp
  • 65
  • 11
  • 1
    This is probably a duplicate of http://stackoverflow.com/questions/15054182/javascript-check-if-file-exists which has an answer that will work for you. – Seemant Kulleen Mar 18 '16 at 10:46
  • this will help you http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – thatOneGuy Mar 18 '16 at 13:01

1 Answers1

1

One way to do this is to use the image, onerror handler:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <script>
      var svg = d3.select('body')
        .append('svg')
        .attr('width', 500)
        .attr('height', 500);
        
      var img = svg.append("image")
        .attr("xlink:href", "doesnotexit.jpeg") //<-- try to load this
        .attr("width", 500)
        .attr("height", 500)
        .attr('onerror', function() { //<-- on no we had troubles!
          d3.select(this)
            .attr("xlink:href", "http://lorempixel.com/500/500/sports");
        });
    </script>
  </body>

</html>
Mark
  • 106,305
  • 20
  • 172
  • 230