检查html画布上特定区域中的点位置

Check a point location in a particular area on html canvas

本文关键字:区域 位置 html 检查      更新时间:2023-09-26

我想检查一个点(x,y)是否在画布上的特定区域中。例如,如果我在html画布上有一个100X100的区域,那么我想知道一个点(x,y)是在这个区域内还是在这个区域外。此检测将使用javascript和jquery来完成。Thanx。

取决于您需要它的用例:

  1. 鼠标悬停/点击:只要你的画布是唯一有移动元素的东西,并且你不需要对safari/iOS的支持,一个好的老式图像地图就可以了。(使用图像地图在画布尺寸上拉伸的1px*1px透明gif)
  2. 任意点(包括鼠标):使用公式计算该点是在多边形内部还是外部。下面的脚本(虽然不是我写的)解决了这个问题:

    //+ Jonas Raoni Soares Silva
    //@ http://jsfromhell.com/math/is-point-in-poly [rev. #0]
    function isPointInPoly(poly, pt){
        for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
            ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
            && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
            && (c = !c);
        return c;
    }
    

    在他的页面上,Jonas还给出了一个如何使用它的例子。基本上,poly是一个包含多边形点的对象数组,pt是一个带有你想要测试的点的对象:

    var polygon = [
        {x: 0, y: 0},
        {x: 0, y: length},
        {x: length, y: 10},
        {x: -length, y: -10},
        {x: 0, y: -length},
        {x: 0, y: 0}
    ];
    var testpoint= {x: 1, y:2};
    if(isPointInPoly(polygon,testpoint)) { /* do something */ }
    

    如果是针对mouseposition,则应该将整个内容绑定到mousemove,在mouseenter/mouseleve时,mousemove-画布节点的所有事件都可以再次启用/禁用

  3. 任意点:使用画布函数isPointInPath(),如下所述:http://canvas.quaese.de/index.php?nav=6,42&doc_id=31尽管AFAIK,但只有当画布上只有一个路径时(可以使用多个画布),或者重新绘制每个多边形并在进行测试时进行测试,这才有效。

我个人更喜欢选项2。如果你需要进一步的帮助来获取鼠标坐标,谷歌搜索应该会在stackoverflow上为你提供正确的页面(或参见右侧的"相关"部分)

步骤1:将您的区域定义为路径。

步骤2:检查给定点是否在此路径内。

// Define path - could be anything, rectangle, circle, polygon etc.
var path = new Path2D();
path.rect(x1, y1, width, height);
// Check if the given point (x2, y2) is inside the path.
if (ctx.isPointInPath(path, x2, y2)) {
    // Point is inside the area
} else {
    // Point is not inside the area
}

如果有多个区域要进行检查,请将每个区域定义为一个路径,并对每个区域进行isPointInPath检查。