# js一些常用的求点的方法

·  阅读 56
`````` /* 线段与线段的交点
* @param {} cp - 贝塞尔曲线
* @param {} b2 - 点
* @return {boolean}
*/
pointOnCubicBezier: function pointOnCubicBezier(cp, t) {
var ax, bx, cx;
var ay, by, cy;
var tSquared, tCubed;
var result = {};
/*计算多项式系数*/
cx = 3 * (cp[1].x - cp[0].x);
bx = 3 * (cp[2].x - cp[1].x) - cx;
ax = cp[3].x - cp[0].x - cx - bx;
cy = 3 * (cp[1].y - cp[0].y);
by = 3 * (cp[2].y - cp[1].y) - cy;
ay = cp[3].y - cp[0].y - cy - by;
/*计算位于参数值t处的曲线点*/
tSquared = t * t;
tCubed = tSquared * t;
result.x = ax * tCubed + bx * tSquared + cx * t + cp[0].x;
result.y = ay * tCubed + by * tSquared + cy * t + cp[0].y;
return result;
},

``````     /** 线段与线段的交点
* @param {Vec2} a1 - The start point of the first line
* @param {Vec2} a2 - The end point of the first line
* @param {Vec2} b1 - The start point of the second line
* @param {Vec2} b2 - The end point of the second line
* @return {boolean}
*/
lineLine: function lineLine(a1, a2, b1, b2) {
var result;
var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
if (u_b != 0) {
var ua = ua_t / u_b;
var ub = ub_t / u_b;
if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
result = new Vec2(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y));
} else {}
} else {
if (ua_t == 0 || ub_t == 0) {} else {}
}
return result;
},

``````/**
* 矩形与线段的交点
* @method lineRect
* @param {Vec2} a1 - The start point of the line
* @param {Vec2} a2 - The end point of the line
* @param {Rect} b - The rect
* @return {boolean}
*/
lineRect: function lineRect(a1, a2, b) {
var points = "";
var r0 = new Vec2(b.x, b.y);
var r1 = new Vec2(b.x, b.yMax);
var r2 = new Vec2(b.xMax, b.yMax);
var r3 = new Vec2(b.xMax, b.y);
if (this.lineLine(a1, a2, r0, r1)) points = this.lineLine(a1, a2, r0, r1); else if (this.lineLine(a1, a2, r1, r2)) points = this.lineLine(a1, a2, r1, r2); else if (this.lineLine(a1, a2, r2, r3)) points = this.lineLine(a1, a2, r2, r3); else if (this.lineLine(a1, a2, r3, r0)) points = this.lineLine(a1, a2, r3, r0);
if (!points) {
var rn = kity.Vector.fromPoints(a1, a2);
var points = bezierLength.lineRect(a1, {
x: a2.x + rn.x + 1,
y: a2.y + rn.y + 1
}, b);
}
return points;
}