更改 xlink:当图像在 D3js 中未退出时 svg 图像的 href 链接

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

本文关键字:图像 svg 退出 链接 href xlink D3js 更改      更新时间:2023-09-26

我正在将SVG图像附加到图表中。但有时图像源可能不存在。为了避免这种情况,我用默认图像替换了un现有图像。

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

假设目录中不存在 d.name+".jpg"。默认情况下,我必须替换它,.jpg。

我该怎么做??

提前谢谢。

一种方法

是使用 image , onerror 处理程序:

<!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>