首页 > 解决方案 > d3.js 不显示图标

问题描述

我一直在尝试使用 d3.js 插入一个图标。但是当我运行它时我没有得到任何图标。这是我的代码片段。

             node = svg.selectAll('g.node')
                   .data(svg_nodes, function (d) {
                        return (d && d.svg_id) || d3.select(this).attr("id");
                    })
             node.select('polygon:nth-of-type(8)') 
                .append("image")
                .attr("xlink:href", "https://github.com/favicon.ico")
                .attr("x", -8)
                .attr("y", -8)
                .attr("width", 16)
                .attr("height", 16);

标签: javascriptsvgd3.js

解决方案


看来您正在将一个附加<image>到一个<polygon>. 图像不是 SVG 多边形的有效子元素,只有动画元素或描述性元素才是有效的子元素 ( MDN )。

允许的儿童包括:

   <animate>, <animateColor>, <animateMotion>, <animateTransform>, <discard>, <mpath>, <set>, <desc>, <metadata>, <title>

由于您无法将图像添加到多边形,因此您需要将其添加到不同的父级,这也意味着将其单独定位。

一般来说,这里有用的方法通常是使用父元素g来定位每个多边形和图像对——这可能会消除单独定位image和定位的需要polygon,但也可以将这些元素作为共同父元素的兄弟元素配对。

看起来您已经有了一个 parent g,我们只需要访问它即可附加到它:

    node.select('polygon:nth-of-type(8)') 
        .each(function() {
            d3.select(this.parentNode)
              .append("image")
              .attr("xlink:href", "https://github.com/favicon.ico")
              .attr("x", -8)
              .attr("y", -8)
              .attr("width", 16)
              .attr("height", 16);
        })

在没有看到更多代码的情况下,无法说出这将如何相对于您想要的图像定位图像,但至少应该附加图像


推荐阅读