Skip to content

Instantly share code, notes, and snippets.

@adamnew123456
Created December 24, 2018 02:49
Show Gist options
  • Save adamnew123456/2e0e2715d3bc413478772dedcd7c931f to your computer and use it in GitHub Desktop.
Save adamnew123456/2e0e2715d3bc413478772dedcd7c931f to your computer and use it in GitHub Desktop.
A sample for generating bezier curves
function interpolate(a, b, ratio) {
return ratio * (b - a) + a;
}
function Point(x, y) {
return {x: x, y: y};
}
function bezier(points, ratio) {
if (points.length < 2) return null;
if (points.length == 2) {
/*
* In the trivial case, we just need to interpolate
* between start and end.
*/
return Point(
interpolate(points[0].x, points[1].x, ratio),
interpolate(points[0].y, points[1].y, ratio));
}
/*
* If there are actually control points, then we need to
* interpolate between eacn segment formed by those points
* (start and end included) and then run bezier on the
* points resulting from those interpolations.
*/
var interpolated = [];
for (var i = 1; i < points.length; i++) {
var prev = points[i - 1];
var current = points[i];
interpolated.push(bezier([prev, current], ratio));
}
return bezier(interpolated, ratio);
}
var points = [
Point(0, 150),
Point(300, 150),
Point(300, 450),
Point(600, 450)
];
var canvas = document.getElementById('dpy');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(points[0].x, points[0].y);
for (var i = 1; i <= 100; i++) {
var point = bezier(points, i / 100);
context.lineTo(point.x, point.y);
}
context.stroke();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment