Javascript 在SVG路径上查找一个点
Javascript 在SVG路径上查找一个点,javascript,d3.js,Javascript,D3.js,我使用d3js绘制一条平滑曲线。然后,我想在曲线上画一个点,但是这个点是随机的,我只有x值。我想得到函数表达式,得到y值和x值。有什么方法可以得到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'
我使用d3js绘制一条平滑曲线。然后,我想在曲线上画一个点,但是这个点是随机的,我只有x值。我想得到函数表达式,得到y值和x值。有什么方法可以得到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');
我当前的图表:
这里有一个函数,用于在一种二进制搜索中查找具有指定x坐标的点:
注意:路径在X上应是单调的,路径上不得有2个点具有相同的X
const findpoint=path,x=>{
让from=0;
让to=path.getTotalLength;
让电流=从+到/2;
设point=path.getPointAtLengthcurrent;
而Math.abspoint.x-x>0.5{
如果点x对于设x=0;这确实是一篇重复的文章,但我添加了一个片段,因为这篇文章已经有好几年的历史了
常数裕度=30;
常数宽度=400;
常数高度=180;
常量图表宽度=宽度-边距*2;
常量图表高度=高度-边距*2;
const data=Array.from{length:10},v,i=>{
返回{
索引:i,,
值:Math.floorMath.random*20+4
}
};
const svg=d3.selectviz
.appendsvg
.宽度,宽度
.身高,身高,;
常量xScale=d3.scaleLinear
.domaind3.extentdata,d=>d.index
.范围[0,图表宽度];
svg.appendg
.attrclass,x轴
.attrtransform,`translate${margin},${height-margin}`
.calld3.axisBottomxScale;
常数yScale=d3.scaleLinear
.domaind3.extentdata,d=>d.value
.范围[图表高度,0];
svg.appendg
.attrclass,y轴
.attrtransform,`translate${margin},${margin}`
.calld3.axisLeftyScale;
常数线=d3.0线
.xd=>xScaled.index
.yd=>yScaled.value
.curved3.curveCatmullRom;
const series=svg.appendg
.attrtransform,`translate${margin},${margin}`
.appendpath
.attrd,linedata
.attrill,透明
.笔划宽度,2
.黄色,橙色;
常量findYFromXLinearTime=x,行=>{
const getXYAtLength=len=>{
const pt=line.getPointAtLengthlen;
返回{x:pt.x,y:pt.y};
}
设l=0;
而getXYAtLengthl.x{
常数误差=0.01;
常数iterMax=50;
设iter=0;
让start=0;
让end=line.getTotalLength;
让点=line.getPointAtLengthend+start/2;
而xpoint.x+错误{
//更新中间
point=line.getPointAtLengthend+start/2;
//试验
x{
const x=document.getElementByIdsomeX.value;
const y=findYFromXLogTimexScalex,series.node;
svg.appendcircle
.attrcx,xScalex+保证金
.损耗,y+裕度
attrr先生,4
.加油,红色
.黑色
};
找到Y
为曲线生成y值时,可以将其保存在数组中。如果你有一个对应的x值数组,你应该能够将它们配对。仅仅调用data[x]难道还不够吗并解析返回的坐标?@qianyuxin我建议将问题标题改为:“在SVG路径上查找一个点”@WillWard如果该点位于两个输入数据点之间,并且整个路径是离散数据的贝塞尔近似值,则将无法工作