测试一个点是否大约在由其他两个点组成的线段上 [英] Test if a point is approximately on a line segment formed by two other points
问题描述
我想确定是否在各点之间以及大约在连接这两个点的线段上单击.
I want to determine if a click is made between to points and roughly on the line segment that connects those two points.
我的问题类似于如何确定一个点在线段上的其他两个点之间?两点:
- 我正在使用javascript工作,并且坐标以整数(像素)
- 该点不必精确地位于线段上.需要公差.
以下代码改编自此答案,但我不知道如何在线段周围插入公差
The following code is adapted from this answer, but I dont know how to insert a tolerance around the line segment
a
和b
是线段的端点,而c
是单击的点.我想检查c
是否在a
和b
之间,并且大致在连接a
和b
a
and b
are the end points of the line segment and c
is the clicked point. I want to check if c
is between a
and b
and roughly on the segment that connects a
and b
PencilTool.prototype._isBetween = function(a,b,c){
//test if a, b and c are aligned
var crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y);
if(Math.abs(crossproduct) !== 0){ return false; }
var dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if(dotproduct < 0){ return false }
var squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);
if(dotproduct > squaredlengthba){ return false; }
return true;
}
推荐答案
这是我现在正在使用的最终javascript函数.
Here is the final javascript function I am now using.
第一部分使用的距离公式如 Ashley Tharp的答案所述,我们首先测试c
是否为在通过a
和b
的线的预定义距离(tolerance
)之内.
The first part is using the distance formula as explained in Ashley Tharp's answer, we first test if c
is inside a pre-defined distance (tolerance
) of a line going through a
and b
.
第二部分摘自 Cyrille Ka'对类似问题的回答.
然后,要知道
c
是否在a
和b
之间,还必须检查(b-a)
和(c-a)
的点积为正且小于 比a
和b
之间的距离的平方.
Then, to know if
c
is betweena
andb
, you also have to check that the dot product of(b-a)
and(c-a)
is positive and is less than the square of the distance betweena
andb
.
// a and b are vertices of the segment AB and c is the tested point (here from a mouseclick event (e))
var a={}, b={}, c={};
a.x = 100;
a.y = 100;
b.x = 200;
b.y = 200;
c.x = e.screenX
c.y = e.screeny
console.log(isBetween(a, b, c, 5));
function isBetween(a, b, c, tolerance) {
//test if the point c is inside a pre-defined distance (tolerance) from the line
var distance = Math.abs((c.y - b.y)*a.x - (c.x - b.x)*a.y + c.x*b.y - c.y*b.x) / Math.sqrt(Math.pow((c.y-b.y),2) + Math.pow((c.x-b.x),2));
if (distance > tolerance) { return false; }
//test if the point c is between a and b
var dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y);
if (dotproduct < 0) { return false; }
var squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);
if (dotproduct > squaredlengthba) { return false; }
return true;
};
这篇关于测试一个点是否大约在由其他两个点组成的线段上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!