Ume*_*iya 2 javascript geometry
我如何得到一条线和一个圆的交点..我得到了很多关于这个主题的信息,但我的要求不匹配..
我得到了一条线,它的一个端点位于圆的原点..而另一端位于圆外的某处..现在我需要这条线和圆的交点..
我试图使用以下公式从圆外找到最近的边缘点,但无法破解它 -
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};
};
Run Code Online (Sandbox Code Playgroud)
有什么办法可以解决这个问题..?? 提前致谢!
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));
}
Run Code Online (Sandbox Code Playgroud)
但是你需要实现向量“类”*你自己:
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());
};
Run Code Online (Sandbox Code Playgroud)
* JavaScript 中没有真正的类——只有构造函数和原型,随着 ES6 的变化,这是另一个话题。
| 归档时间: |
|
| 查看次数: |
3646 次 |
| 最近记录: |