mirror of
https://github.com/scratchfoundation/paper.js.git
synced 2025-01-19 14:10:14 -05:00
Some refactoring and added comments to @sapics code in Curve.getNearestParameter()
This commit is contained in:
parent
cbefa668f4
commit
4678697638
1 changed files with 21 additions and 8 deletions
|
@ -645,16 +645,29 @@ statics: {
|
|||
},
|
||||
|
||||
getNearestParameter: function(v, point) {
|
||||
if (!this.hasHandles(v)) {
|
||||
if (!Curve.hasHandles(v)) {
|
||||
var p1x = v[0], p1y = v[1],
|
||||
p2x = v[6], p2y = v[7],
|
||||
v12x = p2x - p1x, v12y = p2y - p1x,
|
||||
t = ((point.x - p1x) * v12x + (point.y - p1y) * v12y) /
|
||||
(v12x * v12x + v12y * v12y),
|
||||
epsilon = /*#=*/Numerical.EPSILON;
|
||||
if (t < epsilon) return 0;
|
||||
if (t + epsilon > 1) return 1;
|
||||
return 0.5 - Math.cos(Math.acos(2 * t - 1) / 3 + Math.PI * 4 / 3) || 0.5;
|
||||
vx = p2x - p1x, vy = p2y - p1x;
|
||||
// Line has zero length, avoid divisions by zero
|
||||
if (vx === 0 && vy === 0)
|
||||
return 0;
|
||||
// Project the point onto the line and calculate its linear
|
||||
// parameter u along the line:
|
||||
// u = (point - p1).dot(v) / v.dot(v)
|
||||
var u = ((point.x - p1x) * vx + (point.y - p1y) * vy) /
|
||||
(vx * vx + vy * vy);
|
||||
if (u < /*#=*/Numerical.EPSILON)
|
||||
return 0;
|
||||
if (u > /*#=*/(1 - Numerical.EPSILON))
|
||||
return 1;
|
||||
// Now translate the linear u to the curve-time t:
|
||||
// B(t) = (1-t)^3 P0 + 3(1-t)^2 t P1 + 3(1-t)t^2 P2 + t^3 P3
|
||||
// This case is linear, so B(t) = u, with: P0 = P1 = 0, P2 = P3 = 1
|
||||
// -> u = 3(1-t)t^2 + t^3
|
||||
// -> 2 * t^3 - 3 * t^2 + u = 0
|
||||
// We can calculate t from u using the trigonometric method:
|
||||
return 0.5 - Math.cos((Math.acos(2 * u - 1) + Math.PI * 4) / 3);
|
||||
}
|
||||
|
||||
var count = 100,
|
||||
|
|
Loading…
Reference in a new issue