Skip to content

Instantly share code, notes, and snippets.

@sakyaer
Forked from LiuJi-Jim/bezier.js
Created May 16, 2016 03:50
Show Gist options
  • Save sakyaer/261827bc8d84479484be449584e096f8 to your computer and use it in GitHub Desktop.
Save sakyaer/261827bc8d84479484be449584e096f8 to your computer and use it in GitHub Desktop.
De Casteljau Bezier
function DeCasteljauBezier(points, density, step){
//if (points.length < 3) return null;
console.time('bezier');
var ps = points.map(function(p){
return {
x: p.x,
y: p.y
};
}),
results = [],
len = ps.length,
epsilon = 0.00001;
density = density || 20; // 密度,决定了采样精度(曲线平滑程度)
step = step || 0.00001; // bezier递推步长
var dest = {
x: points[points.length-1].x,
y: points[points.length-1].y
};
var mindist = pow(density, 2);
results.push({
x: ps[0].x,
y: ps[0].y
});
// 递推
for (var t=0; t<=1; t+=step){
for (var i=1; i<len; ++i){
for (var j=0; j<len - i; ++j){
ps[j].x = ps[j].x * (1 - t) + ps[j + 1].x * t;
ps[j].y = ps[j].y * (1 - t) + ps[j + 1].y * t;
}
}
var now = {
x: ps[0].x,
y: ps[0].y
}
if (pow(now.x-dest.x, 2) + pow(now.y-dest.y, 2) < epsilon){
break;
}
results.push(now);
}
// 采样
var last = results[0];
var results2 = [last];
for (var i=1; i<results.length; ++i){
var now = results[i];
var dist = pow(now.x-last.x, 2) + pow(now.y-last.y, 2);
if (dist >= mindist){
results2.push(now);
last = now;
}
}
results2.push(dest);
//console.log(results.length, results2.length);
console.timeEnd('bezier');
return results2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment