gpt4 book ai didi

javascript - 在 d3.arc 属性中使用函数

转载 作者:行者123 更新时间:2023-11-30 19:18:15 25 4
gpt4 key购买 nike

我想将每个弧的 startAngle 设置为我的数据中的一个属性。但是,当我尝试使用与使用“rect”设置宽度相同的方法时,该函数不会运行...

我试图在这个例子中复制我获得宽度的方式(对于 'rect'):

            svg.selectAll('rect').data(data)
.enter().append('rect')
.attr('width', d => d.duration) // <-----
.attr('height', 100)

但是当我对 arc 做同样的事情时,函数失败了:

            dogn.selectAll('path').data(data)
.enter().append('path')
.attr('d', d3.arc()({
innerRadius: ringWidth,
outerRadius: (ringWidth / 1.25),
startAngle: d => d.duration, // <-----
endAngle: 2*Math.PI
}));

如何让startAngle成为对应的

使用 startAngle 函数时出现以下错误:

Error: <path> attribute d: Expected number, "MNaN,NaNL-2.20436…".

最佳答案

当您对矩形执行此操作时...

.attr('width', d => d.duration)

...您正在检索匿名函数中的绑定(bind)数据,这是它的第一个参数(习惯上命名为 d,但您可以使用任何名称)。

但是,对于您的弧,您没有检索任何绑定(bind)数据,对象 d 根本不存在。

解决方案是将所有 d3.arc 包装在一个匿名函数中,该函数接收第一个参数:

.attr('d', function(d) {
//1st argument----^
return d3.arc()({
innerRadius: ringWidth,
outerRadius: (ringWidth / 1.25),
startAngle: d.duration,//using the bound datum here
endAngle: 2 * Math.PI
})
});

这是一个演示,看看每条弧线如何有不同的起始 Angular (以弧度为单位):

const svg = d3.select("svg")
.append("g")
.attr("transform", "translate(150,75)");
const data = [0.5, 1, 2];
const arcs = svg.selectAll(null)
.data(data)
.enter()
.append('path')
.attr('d', function(d, i) {
return d3.arc()({
innerRadius: 20 + i * 10,
outerRadius: 30 + i * 10,
startAngle: d,
endAngle: 2 * Math.PI
})
})
.style("fill", function(_, i) {
return d3.schemeCategory10[i]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

关于javascript - 在 d3.arc 属性中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com