如何捕获 svg 图像在 D3 中加载失败的情况?

use*_*812 7 load image d3.js

我正在使用 D3 创建包含多行<image>svg 元素的可视化。

如果图像文件不可用,有人知道如何上传替换图像吗?

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

           })
Run Code Online (Sandbox Code Playgroud)

Lud*_*ltz 5

我知道这是一篇旧帖子,但我找到了一个比马克答案更简单的解决方案。所以我将其发布给未来遇到同样问题的用户。

d3.jsclick中,您可以在节点( 、load、 ...)上添加事件侦听器error。因此,当图像加载失败时,您可以将链接(带有setAttribute()功能)更改为后备图像。这是一个工作示例(请注意,您不应xlink:在 之前添加href):

var images = imageGroup.append('svg:image')
    .attr("href", function(d){
        return "ThisImageWillFailsToLoad.jpg"
    })
    .on("error", function(d){
        this.setAttribute("href", "YourFallbackImage.jpg");
    })
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 3

这更像是一个 JavaScript 问题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>
Run Code Online (Sandbox Code Playgroud)