1 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是一個(gè)使用 vanilla javascript 而不是 d3 的演示,但我希望你會(huì)發(fā)現(xiàn)它很有用。
該函數(shù)getLengthForPoint(p,thePath)正在計(jì)算給定點(diǎn) p 在路徑上的距離。我正在設(shè)置一個(gè)變量let precision = 100;。根據(jù)路徑的長(zhǎng)度,您可能希望將此值更改為其他值。
還要記住,一條路徑可以多次通過(guò)同一個(gè)點(diǎn)。這可能很棘手,并且可能會(huì)給您帶來(lái)錯(cuò)誤。
同樣如您所知,您將獲得到某個(gè)點(diǎn)的近似距離。在這個(gè)例子中,點(diǎn)p1 = {x:93.5,y:60}. 計(jì)算長(zhǎng)度處的點(diǎn)具有以下坐標(biāo):{x:93.94386291503906,y: 59.063079833984375}
// some points on the path
let p1 = {x:93.5,y:60}
let p2 = {x:165,y:106}
//the total length of the path
let pathLength = thePath.getTotalLength();
let precision = 100;
let division = pathLength / precision;
function getLengthForPoint(p,thePath){
let theRecord = pathLength;
let theSegment;
for (let i = 0; i < precision; i++) {
// get a point on the path for thia distance
let _p = thePath.getPointAtLength(i * division);
// get the distance between the new point _p and the point p
let theDistance = dist(_p, p);
if (theDistance < theRecord) {
// if the distance is smaller than the record set the new record
theRecord = theDistance;
theSegment = i;
}
}
return(theSegment * division);
}
let theDistanceOnThePath = getLengthForPoint(p1,thePath);
//if you calculate the coords of a point at the calculated distance you'll see that is very near the point
console.log(thePath.getPointAtLength(theDistanceOnThePath));
let theDistanceBetween2PointsOnThePath = getLengthForPoint(p2,thePath) - getLengthForPoint(p1,thePath);
// a helper function to measure the distance between 2 points
function dist(p1, p2) {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
svg{border:solid}
<svg viewBox="0 10 340 120">
<path id="thePath" fill="none" stroke="black" d="M10, 24Q10,24,40,67Q70,110,93.5,60Q117,10,123.5,76Q130,142,165,106Q200,70,235,106.5Q270,143, 320,24"></path>
<circle cx="93.5" cy="60" r="2" fill="red"/>
<circle cx="165" cy="106" r="2" fill="red"/>
</svg>
要獲得路徑上兩點(diǎn)之間的距離,您可以執(zhí)行以下操作:
let theDistanceBetween2PointsOnThePath = getLengthForPoint(p2,thePath) - getLengthForPoint(p1,thePath);
添加回答
舉報(bào)