【问题标题】:Cleaner and better way to select and change colour of circles in d3在 d3 中选择和更改圆圈颜色的更清洁和更好的方法
【发布时间】:2021-07-28 04:02:18
【问题描述】:

在玩了很多之后,我设法让下面的函数一次改变了我所有 7 个圆圈的颜色。有一个可变颜色,它是一个颜色字符串数组。

这是我的功能:

function colorSquares(){
    for(let i = 0; i<7 ; i++){
        let id = '#s' + i ;
        d3.select(id).attr('fill',colors[i]);
     }
}

我不禁想到有一种更简单的方法可以做到这一点!我创建了这样的 7 个圆圈:

for(let i = 0 ; i< 7; i++){
    const circle = d3.select('.canvas')
        .append('circle')
            .attr('cx', 70 + i* 50)
            .attr('cy', 100)
            .attr('r', 20)
            .attr('stroke' ,'grey')
            .attr('stroke-width', 5)
            .attr('id' , 'c'+i );

}

如您所见,我手动创建了一个字符串,并使用 .attr 将其添加到每个圆圈中,然后用字符串乱七八糟地调用这个圆圈。有没有人有更清洁和更好的方法来做到这一点,有效地我正在寻找更好的方法来创建然后选择圆圈,这样我就不必将字符串作为 ID 搞砸

【问题讨论】:

  • 您还应该使用 selectAll 来创建所有圆圈 - D3 通常旨在避免创建或更新循环:var circles = d3.select('.canvas').selectAll("circle").data(d3.range(7)).enter().append("circle").attr("cx", d=&gt; 70 + i * 50.... 然后您可以重用 circles 变量稍后更改它们,而不是而不是再次选择它们。
  • @AndrewReid 谢谢安德鲁!我只是设法完成这项工作并节省了大约 10 行代码:)
  • 使用 var circles = 与 const circles = 相比有什么优势吗?

标签: javascript d3.js


【解决方案1】:

试试

d3.select('.canvas')
  .selectAll('circle')
  .attr('fill', (d, i) => colors[i]);

【讨论】:

  • 这很棒!你能解释一下为什么我们需要 (d, i) => colors[i])。当我只尝试 i => colors[i]) 时它不起作用:)
  • 因为第一个参数是当前数据(约定为d),第二个参数是当前索引(约定为i):见github.com/d3/d3-selection#selection_attr
猜你喜欢
  • 1970-01-01
  • 2020-08-20
  • 2012-06-27
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多