我如何获得直线和圆的交点..我获得了有关此主题的很多信息,但是我的要求不匹配。
我得到了一条线,其端点位于圆的原点..而另一端位于圆的外部。.现在,我需要此线与圆的交点。
我试图使用以下公式从圆的外部找到最近的边缘点,但是无法破解-
closestCirclePoint = function(px, py, x, y, ray){
var tg = (x += ray, y += ray, 0);
return function(x, y, x0, y0){return Math.sqrt((x -= x0) * x + (y -= y0) * y);}(px, py, x, y) > ray ?
{x: Math.cos(tg = Math.atan2(py - y, px - x)) * ray + x, y: Math.sin(tg) * ray + y}
//{x: (px - x) / (length / ray) + x, y: (py - y) / (length / ray) + y}
: {x: px, y: py};
};
任何方式都可以解决此问题。
提前致谢!
最佳答案
Lindenhovius答案的JavaScript版本如下所示:
/**
* Finds the intersection between a circles border
* and a line from the origin to the otherLineEndPoint.
* @param {Vector} origin - center of the circle and start of the line
* @param {number} radius - radius of the circle
* @param {Vector} otherLineEndPoint - end of the line
* @return {Vector} - point of the intersection
*/
function findIntersect (origin, radius, otherLineEndPoint) {
var v = otherLineEndPoint.subtract(origin);
var lineLength = v.length();
if (lineLength === 0) throw new Error("Length has to be positive");
v = v.normalize();
return origin.add(v.multiplyScalar(radius));
}
但是您需要自己实现 vector “类” *:
function Vector (x, y) {
this.x = x || 0;
this.y = y || 0;
}
Vector.prototype.add = function (vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
};
Vector.prototype.subtract = function (vector) {
return new Vector(this.x - vector.x, this.y - vector.y);
};
Vector.prototype.multiply = function (vector) {
return new Vector(this.x * vector.x, this.y * vector.y);
};
Vector.prototype.multiplyScalar = function (scalar) {
return new Vector(this.x * scalar, this.y * scalar);
};
Vector.prototype.divide = function (vector) {
return new Vector(this.x / vector.x, this.y / vector.y);
};
Vector.prototype.divideScalar = function (scalar) {
return new Vector(this.x / scalar, this.y / scalar);
};
Vector.prototype.length = function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
};
Vector.prototype.normalize = function () {
return this.divideScalar(this.length());
};
* JavaScript中没有真正的类-只是constructor functions和prototypes,随着ES6的改变,但这是另一个主题。