【问题标题】:How to catch svg image fail to load in D3?如何捕获 svg 图像无法在 D3 中加载?
【发布时间】:2016-10-11 23:10:10
【问题描述】:

我正在使用 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"

           })

【问题讨论】:

    标签: image d3.js load


    【解决方案1】:

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

    在 d3.js 中,您可以在节点上添加事件监听器(click、load、error、...)。因此,当图像无法加载时,您可以将链接(使用setAttribute() 函数)更改为备用图像。这是一个工作示例(请注意,您不应在 href 之前添加 xlink: ):

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

    【讨论】:

      【解决方案2】:
      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");
        });
      

      【讨论】:

      • @altocumulus 我在代码中添加了解释。可能有些地方没有解释清楚。如果你不明白,你可以问我,我会改进解释。我在自己的项目中实践过,是可行的。
      【解决方案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>

      【讨论】:

        猜你喜欢
        • 2016-05-02
        • 2021-01-10
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 2014-07-27
        • 1970-01-01
        • 2014-03-10
        相关资源
        最近更新 更多