Skip to content

Instantly share code, notes, and snippets.

@cleure
Last active April 15, 2016 15:33
Show Gist options
  • Save cleure/f9f95f72ffb6c2bcfb31c9feb6ebc0b1 to your computer and use it in GitHub Desktop.
Save cleure/f9f95f72ffb6c2bcfb31c9feb6ebc0b1 to your computer and use it in GitHub Desktop.
Generates a bezier curve, at a given sample-rate.
module.exports = {
getPoints: getPoints
};
/**
* Generates a bezier curve at sameple rate nSamples, given an array of points
* @param {Number} nSamples
* @param {Array<Number>} points
* @returns {Array<Number>}
*/
function getPoints(nSamples, points) {
var output = [];
var xy_items = points.length / 2;
var pascal_row = pascalsTriangle.getRow(xy_items - 1);
for (var i = 0; i < nSamples; i++) {
var t = (1.0 / (nSamples - 1)) * i;
var sumx = 0;
var sumy = 0;
for (var j = 0; j < xy_items; j++) {
var coef = (
pascal_row[j] *
Math.pow(t, j) *
Math.pow(1 - t, xy_items - (j + 1))
);
sumx += coef * points[j * 2];
sumy += coef * points[j * 2 + 1];
}
output.push(sumx);
output.push(sumy);
}
return output;
}
var pascalsTriangle = {
getRow: function (n) {
var row = [1];
var numerator = n;
var x = 1;
var l = Math.floor((n / 2) + 1);
var i;
// Fill first half of array.
for (i = 1; i < l; i++, numerator--) {
x = Math.round((x * numerator) / i);
row.push(x);
}
// Depending on if n is even or odd will determine whether or not we need
// to read from one space back in row, or two.
x = n % 2 === 1 ? i - 1 : i - 2;
// Fill second half of array.
for (; i <= n; i++, x--) {
row.push(row[x]);
}
return row;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment