如何在 JavaScript 中处理线段、检查点
我有以下代码:
Object.defineProperty(LineSegment.prototype,'hasPoint',{ value:
function (point) {
if (typeof point != 'object' || !(point instanceof Point)) {
throw new TypeError('LineSegment.prototype.hasPoint requires a point value.'); }
var m = (this.y1 - this.y2) / (this.x1 - this.x2);
return (this.y1 - point.y) / (this.x1 - point.x) == m; }
});
它适用于线条,但不适用于线段。我如何检查该点是否超出范围,并将其应用于 JavaScript?
I have the following code:
Object.defineProperty(LineSegment.prototype,'hasPoint',{ value:
function (point) {
if (typeof point != 'object' || !(point instanceof Point)) {
throw new TypeError('LineSegment.prototype.hasPoint requires a point value.'); }
var m = (this.y1 - this.y2) / (this.x1 - this.x2);
return (this.y1 - point.y) / (this.x1 - point.x) == m; }
});
It works fine for lines, but not line segments. How would I check if the point is out of bounds, and apply it to JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅当 x1 < 时才能使用最简单且最快的答案。 x2。在这种情况下,返回语句如下:
第一部分检查点是否在线上,接下来的两个条件检查 x 坐标是否在 x1 和 x2(含)之间。
注:若x2< x1,您可以简单地在构造函数中添加一个条件来交换两个点。您还可以以 p+q*v 的形式更改点(其中 p 是直线的第一个点,q 是第二个点,va 标量值,只有当点在线上时才可能)。如果 v 介于 0 和 1(含)之间,则该点在线段上。
编辑:只是警告,由于计算机处理双打的方式,您的方法不会非常可靠。请参阅维基百科页面以获取一些示例:http://en.wikipedia.org/wiki/Double_ precision
The easiest and fastest answer can only be used if x1 < x2. In that case, the following return statement:
The first part checks if the point is on the line, the two next conditions check if the x coordinate is between x1 and x2 (inclusive).
Note: if x2 < x1, you can simply add a condition in the constructor to swap the two points. You could also change the point in the form p+q*v (where p is the first point of the line, q the second and v a scalar value, this is only possible if the point is on the line). If v is between 0 and 1 (inclusive), the point is on the line segment.
EDIT: Just a warning, your method won't be very reliable, because of the way computers handle doubles. See the wikipedia page for some examples: http://en.wikipedia.org/wiki/Double_precision