我想找出图像区域中是否存在给定点。图像宽度和高度为40.四个角是(10,10),(50,10),(10,50),(50,50)。有没有办法在该区域内找到给定的(x,y)是否存在?
答案 0 :(得分:0)
检查点是否位于矩形内部,我使用线方程并将该点与所有四条线进行比较。 这种方法的关键是点序列。
检查以下代码: -
function isPointInside(fourPointsArray, pointToCheck) {
var counter = 0;
var ele = pointToCheck;
var A, B, C, D, p1, p2, indx;
for (var k = 0; k < fourPointsArray.length; k++) {
p1 = fourPointsArray[k];
indx = k + 1;
if (indx >= fourPointsArray.length)
indx = 0;
p2 = fourPointsArray[indx];
A = -(p2.y - p1.y);
B = p2.x - p1.x;
C = -(A * p1.x + B * p1.y);
D = A * ele.x + B * ele.y + C;
if (D >= 0) {
counter++;
}
}
if (counter >= fourPointsArray.length) {
return true;
}
return false;
}
var arraypoints=[{x:10,y:10},{x:50,y:10},{x:50,y:50},{x:10,y:50}];
var pointtocheck={
x:5,
y:10
}
var flag=isPointInside(arraypoints,pointtocheck);
console.log(flag);