Find Point along Bezier Curve in JavaScript

I adapted a C++ implementation to demonstrate finding points along Bezier curves using the DeCasteljau Algorithm. The project supports interpolating vector art from Adobe Illustrator for an HTML5 game-like application.

Core Implementation

The solution uses a module pattern exposing two main functions:

Point Constructor: Creates coordinate objects with x and y properties.

Linear Interpolation: The interpolateLinear function returns a point between two points based on a time value between 0 and 1.

Bezier Calculation: The calc method recursively applies linear interpolation across four control points and a time parameter, executing the DeCasteljau algorithm.

var bezier = (function(){
    var Point = function (x, y) {
        this.x = x || 0;
        this.y = y || 0;
        return this;
    }
    var interpolateLinear = function (pointA, pointB, time) {
        return {
            x: pointA.x + (pointB.x - pointA.x) * time,
            y: pointA.y + (pointB.y - pointA.y) * time,
        }
    }

    var bezObj = {
        point: function(x, y) {
            return new Point(x, y);
        },

        calc: function(p1, p2, p3, p4, time) {
            var ab = interpolateLinear(p1, p2, time),
                bc = interpolateLinear(p2, p3, time),
                cd = interpolateLinear(p3, p4, time),
                abbc = interpolateLinear(ab, bc, time),
                bccd = interpolateLinear(bc, cd, time);

            return interpolateLinear(abbc, bccd, time);
        },
    }
    return bezObj;
}());

Usage Example

myPointA = bezier.point(40, 100);
myPointB = bezier.point(80, 20);
myPointC = bezier.point(150, 180);
myPointD = bezier.point(260, 100);

resultPoint = bezier.calc(
    myPointA, myPointB, myPointC, myPointD,
    0.5 // time parameter
);

The HTML5 canvas demonstration animates the curve by moving control points and rendering points along the path at regular intervals. Note that requestAnimationFrame would be preferable to setInterval for production use.

Credits: Based on work by Nils Pipenbrinck (Submissive/Cubic & $eeN)

Originally published on blog.mikerandrup.com

Back to Home