简体   繁体   中英

Get distance between two SVG paths javascript

I have two SVG paths, a and b, that I want to find the distance between. Distance varies along each point, so in my case, I want to find the smallest distance between these two paths. Is there a way to do this using javascript?

 path { fill: none; }
 <svg xmlns="http://www.w3.org/2000/svg"> <path d="M0,0 Q30,30,0,60" stroke="black"></path> <path d="M70,0 Q30,30,70,60" stroke="black"></path> <path d="M15,30 L50,30" stroke="red"></path> </svg>

In this example, I define the longest path to be the red line.

As an addition, is there any way to find the direction that this is pointing? For example, if the distance method is path1.distance(path2) , could i get the distance as represented by a vector from the point on path1, to the point on path2? If this is not in the scope of your answer, that is fine.

  • Iterate over path a calling getPointAtLength on path a

  • Within the above loop, iterate over path b calling getPointAtLength on path b

  • Use pythagoras theorem to determine the distance between the points in the inner and outer loops. You have the vector because you have the pairs of points.

  • Whatever is the smallest distance is your answer.

  • If you increase the granularity of iteration your answer will be more accurate but take longer.

  • Note that if your paths are parallel lines then there may be an infinite number of nearest points.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM