Last active
July 12, 2020 06:17
-
-
Save LiuJi-Jim/8198646 to your computer and use it in GitHub Desktop.
De Casteljau Bezier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
需要把 pow 替换成 Math.pow() 函数 ;Math.pow(now.x-dest.x, 2);