【问题标题】:d3.js is not showing iconsd3.js 不显示图标
【发布时间】:2020-12-15 10:10:41
【问题描述】:

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

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

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

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

    允许的孩子包括:

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

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

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

    您似乎已经有一个父 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);
            })
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2019-05-02
      • 1970-01-01
      • 2016-12-30
      相关资源
      最近更新 更多