gpt4 book ai didi

javascript - 在 SVG 路径上找到一个点

转载 作者:行者123 更新时间:2023-12-04 01:03:26 29 4
gpt4 key购买 nike

我用d3js画了一条平滑的曲线。然后,我想在曲线上画一个点,但是这个点是随机的,我只有 x 值。我想获取函数表达式并使用 x 值获取 y 值。有什么方法可以得到y值吗?

const line = d3.line()
.x(d => xScale(new Date(d.name)))
.y(d => yScale(d.value1))
.curve(d3.curveCatmullRom);
const series = svg.append('g')
.attr('transform', `translate(${grid.left},${grid.top})`)
.append('path')
.attr('d', line(data))
.attr('fill', 'transparent')
.attr('stroke-width', 2)
.attr('stroke', 'orange');

我目前的图表: the chart I draw current

最佳答案

这是一个函数,它在 <path> 上找到具有指定 x 坐标的点(一种二进制搜索):

注意:路径在X上应该单调(路径上不能有2个点具有相同的x)

const findPointAt = (path, x) => {
let from = 0;
let to = path.getTotalLength();
let current = (from + to) / 2;
let point = path.getPointAtLength(current);

while (Math.abs(point.x - x) > 0.5) {
if (point.x < x)
from = current;
else
to = current;
current = (from + to) / 2;
point = path.getPointAtLength(current);
}
return point;
}


const path = d3.select('path').node();

for (let x = 0; x <= 200; x += 50) {
const pos = findPointAt(path, x);
console.log(pos);
d3.select('svg').append('circle')
.attr('cx', pos.x)
.attr('cy', pos.y)
.attr('r', 3)
}
svg {
border: 1px solid gray;
}

path {
fill: none;
stroke: blue;
}

circle {
fill: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<svg width="200" height="150">
<path d="M 0,10 Q 40,0 90,80 C 120,120 150,70 220,20" />
</svg>

关于javascript - 在 SVG 路径上找到一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67331467/

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