The Shape of Everything
A website mostly about Mac stuff, written by Gus Mueller
» Acorn
» Twitter
» Maybe Pizza?
» Code
» Archive
January 5, 2013

Unasked for, an algorithm rudely popped into my head while taking a shower this morning. I couldn't shake it from my head so I decided to code it up in JSTalk:

What you're looking at is a little recursive search to find the closest point on a bezier curve to another point (which in the case of my code, is the location of the mouse). The blue line is the curve, the red dots on the curve are the locations of the various stops along the way to eventually finding the black dot, which represents the closest location to the middle of the big green circle (where the mouse is). There's another red dot in that circle which is the mouse location.

I also made a quick video of it in action with some commentary: closestpointoncurve.mp4

I'm not sure what to use it for yet, but I've got some ideas.

You can look at the code here: Code Sketcher Close To Bezier.jstalk. Note: this requires a build of JSTalk from the experimental GitHub folder (which someday will turn into JSTalk 2.0).

Update: And now that I think about it a bit more, this algorithm won't work for all bezier curves and will give you bad results if a curve comes close to crossing back on itself. I'll have to revisit this another day when I finally come up with a need for it.

Update 2: Yea, I was very wrong with my original implementation. I've added a new one to the script, and a little explanation with a video: closestpointoncurvetake2.mp4