简体   繁体   中英

Change xlink:href link of svg image when image does not exits in D3js?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM