d3:如何在if条件下为圆形添加边框?

5
我正在为我的d3图表添加一些圆形,如下所示:

 this.node = this.svg.append('g')
    .attr('class', 'nodes')
  .selectAll('circle')
  .data(graph.nodes)
  .enter().append('circle')
    .attr('r', 5)
    .attr('fill', (d) => { return this.color(d.group); })
    .on('click', this.mouseclick)
    .call(d3.drag()
        .on('start', this.dragstarted)
        .on('drag', this.dragged)
        .on('end', this.dragended));

就像上面使用的 d.group 一样,我的数据中也有 d.error,它可以是 truefalse。如果 d.error === true,在节点被添加时(或之后)如何显示相同节点的红色边框?

1个回答

11

如果d.error的条件为false,则可以应用transparent stroke;否则应用red

.style("stroke", d => d.error ? "red" : "transparent")

使用undefined代替transparent同样可行:

.style("stroke", d => d.error ? "red" : undefined)
// which can also be written:
.style("stroke", d => { if (d.error) return  "red" })

以下是一个演示:

d3.select("svg").attr("width", 500).attr("height", 500)
  .selectAll("circle")
  .data([{ x: 85, y: 80, r: 35, error: true }, { x: 265, y: 124, r: 45, error: false }])
  .enter().append("circle")
    .attr("transform", d => "translate(" + d.x + "," + d.y + ")")
    .attr("r", d => d.r)
    .style("fill", "blue")
    .style("stroke", d => d.error ? "red" : "transparent");
  
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<svg></svg>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接