Skip to content

Instantly share code, notes, and snippets.

@itorr
Last active January 27, 2016 07:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itorr/63e0827a06ae41bb4ac2 to your computer and use it in GitHub Desktop.
Save itorr/63e0827a06ae41bb4ac2 to your computer and use it in GitHub Desktop.
通过前后两点计算中心点三次贝塞尔平滑时的手柄位置
var
calc={};
//通过两点计算斜率
calc.slope=function(A,B){
return (B.y-A.y)/(B.x-A.x);
};
//通过斜率+单点计算截距
calc.intercept=function(slope,A){
//y=kx+b;
return A.y-slope*A.x;
};
//通过两条斜线计算交叉点位置
calc.intersection=function(slopeA,interceptA,slopeB,interceptB){
R={};
R.x=(interceptB-interceptA)/(slopeA-slopeB);
R.y=slopeA*R.x+interceptA;
/*
slopeAD*D.x+interceptAD=slopeDE*D.x+interceptDE
slopeAC*x+interceptAC=slopeAD*x+interceptAD;
x=(slopeAC*x+interceptAC-interceptAD)/slopeAD;
k1x+b1=k2x+b2
(interceptAD-interceptAC)/(slopeAC-slopeAD);
//等式联立
(
D.y=slopeAD*D.x+interceptAD;
D.y=slopeDE*D.x+interceptDE;
)
D.y=slopeDE*D.x+interceptDE;
=>
D.y-interceptDE=slopeDE*D.x;
=>
(D.y-interceptDE)/slopeDE=D.x;
D.y=slopeAD*(D.y-interceptDE)/slopeDE+interceptAD;
*/
return R;
};
/*通过前后两个中点和中心点返回两个调整点位置 A C 分别为前后点*/
calc.point2grip=function(A,B,C){
//line AC 斜率
slopeAC=calc.slope(A,C);
//line AC 截距
interceptAC=calc.intercept(slopeAC,A);
//line DE 斜率
slopeDE=slopeAC;
//line DE 截距
interceptDE=calc.intercept(slopeDE,B);
//console.log(/验证线DE的公式是否正确/,B.y==slopeDE*B.x+interceptDE);
//line AD 斜率
//垂直的线之间,斜率关系为 a=-1/b
slopeAD=-1/slopeAC;
//line AD 截距
interceptAD=calc.intercept(slopeAD,A);
//console.log(/验证线AD的公式是否正确/,A.y==slopeAD*A.x+interceptAD);
//求得 D 点位置
D=calc.intersection(slopeAD,interceptAD,slopeDE,interceptDE);
//line CE 斜率
slopeCE=slopeAD;
//line CE 截距
interceptCE=calc.intercept(slopeCE,C);
//求得 E 点位置
E=calc.intersection(slopeCE,interceptCE,slopeDE,interceptDE);
return [D,E];
};
//测试
A={
x:10,
y:40
};
B={
x:40,
y:20
};
C={
x:70,
y:50
};
var
r=calc.point2grip(A,B,C);
console.log(r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment