【问题标题】:D3.js Invisible rect element when using d3 append to add "rect" elements to an svgD3.js 使用 d3 append 将“rect”元素添加到 svg 时不可见的 rect 元素
【发布时间】:2021-02-01 09:14:09
【问题描述】:

我有这个代码 sn-p,我使用 D3.js 创建一个 1 列网格,颜色由十六进制代码数组给出。我已将每个矩形元素的 y 位置设置为 i*height(其中 i 是颜色十六进制代码的索引)。在输出中我可以看到 rect 元素,但最后一个(红色)是不可见的。

当我检查我的 HTML 时,我可以看到它在我需要的地方,它只是不可见的。如何调整我的代码以使最后一个矩形可见?

let colors=['#2A4DE8','#2AA3E8', '#F6922E','#F62E2E'];


let legend=d3.select('#legend');

legend.selectAll('rect')
      .data(colors)
      .enter()
      .append('rect')
      .attr('fill', (color)=>{return color})
      .attr('width', '50px')
      .attr('height', '50px')
      .attr('x', '0px')
      .attr('y', (color,index)=>{return index*50})
    
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>

<svg id="legend"></svg>

【问题讨论】:

  • 在大多数浏览器中,SVG 的默认高度为 150 像素,正如我在这里回答的那样:stackoverflow.com/a/40156993/5768908
  • 谢谢,有帮助。我现在将我的高度设置为 200 像素,现在它非常适合。

标签: javascript d3.js


【解决方案1】:

我将 let legend=d3.select('#legend'); 更改为 let legend=d3.select('#legend').attr("height", "200px"); 以覆盖 150 像素的默认 svg 高度。

[参见 https://stackoverflow.com/a/40156993/5768908]

let colors=['#2A4DE8','#2AA3E8', '#F6922E','#F62E2E'];


let legend=d3.select('#legend').attr("height", "200px");

legend.selectAll('rect')
      .data(colors)
      .enter()
      .append('rect')
      .attr('fill', (color)=>{return color})
      .attr('width', '50px')
      .attr('height', '50px')
      .attr('x', '0px')
      .attr('y', (color,index)=>{return index*50})
    
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>

<svg id="legend">
       
</svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-13
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多