Skip to content

Instantly share code, notes, and snippets.

@jkiss
Last active March 26, 2019 04:59
Show Gist options
  • Save jkiss/b8fa1bb39c108dfa1a5a236fc08e7d1f to your computer and use it in GitHub Desktop.
Save jkiss/b8fa1bb39c108dfa1a5a236fc08e7d1f to your computer and use it in GitHub Desktop.
Cubic Bezier Curve function from control points
/**
* Create cubic bezier curve function from 4 points
*
* @param {Plain Object} p0 : start point
* @param {Plain Object} p1 : first control point
* @param {Plain Object} p2 : second control point
* @param {Plain Object} p3 : end point
*/
function BezierCubicXY(p0, p1, p2, p3){
this.coords = ['x', 'y'];
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
BezierCubicXY.prototype.xy = function(t) {
var _me = this,
ret = {};
_me.coords.forEach(function(k){
ret[k] = Math.pow(1 - t, 3) * _me.p0[k] + 3 * Math.pow(1 - t, 2) * t * _me.p1[k] + 3 * (1 - t) * Math.pow(t, 2) * _me.p2[k] + Math.pow(t, 3) * _me.p3[k];
})
return ret;
}
// Usage
console.log('BezierCubicXY', (new BezierCubicXY({x: 225, y: 100}, {x: 132.5, y: 100}, {x: 132.5, y: 20}, {x: 40, y: 20})).xy(0.5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment