Search code examples
containspointbezier

How can I tell if a point is on a quadratic Bézier curve within a given tolerance?


I'm writing a library for Bézier curves. I already can calculate the curve as a collection of connected points to a given resolution, but I now need to do the reverse; detect whether a given point is on the curve within a given tolerance (e.g. 0.0001). Is there a simple mathematical function that can do this?

Please phrase your answer in the form of a function that takes in three parameters: the x and y coordinates and a tolerance (distance from curve still considered "on" it), and which outputs a Boolean value. This will make it more generally useful to others. For example, such a function in Swift would have the signature func isOnCurve(x: Float, y: Float, tolerance: Float) -> Bool


Solution

  • You could exploit the "distance to curve" method described over at https://pomax.github.io/bezierinfo/#projections, but this will find a single t value for any coordinate. For "is this point on the curve?" checks, that's fine (multiple t values do not change the answer; 0 is off-curve, 1 is on-curve, 2 or more is still on-curve).

    Sample the curve at a few (relatively close-spaced) values for t (which I assume for efficiency you already do in order to only compute draw coordinates once, rather than every time the curve needs to be drawn), and then with the closest t that yields, start walking the curve, reducing the distance until you've found the minimal distance (how you walk is up to you: you can do a coarse-to-fine walk, or start off fine, or determine how far to jump based on the curve tangent, etc).

    Then your result is literally just return minDistance <= tolerance.