了解CanvasRenderingContext2D.isPointInPath()

    简介

    CanvasRenderingContext2D.isPointInPath()用来检测某个点是否在当前路径中。

    检测路径就变成了这次beginPath()之后绘制的路径,原来的路径不会参与检测。,需要注意的是,当我们每次执行一次beginPath()方法

    语法

    context.isPointInPath(x, y);
    context.isPointInPath(x, y, fillRule);
    // 下面语法IE不支持
    context.isPointInPath(path, x, y);
    context.isPointInPath(path, x, y, fillRule);

    此方法返回Boolean值。

    参数

    各个参数含义和作用如下:

    x
    Number
    用来检测的点的横坐标。
    y
    Number
    用来检测的点的纵坐标。
    fillRule
    String
    填充规则。用来确定一个点实在路径内还是路径外。可选值包括:
    • nonzero:非零规则,此乃默认规则。
    • evenodd:奇偶规则。

    关于'nonzero''evenodd'规则可参见这篇文章

    path
    Object
    指Path2D对象。

    案例

    在Canvas画布上画两个圈圈,然后看看圈内圈外圈上这几个点的返回值是什么,代码如下:

    // 画一个圆
    context'arc]120} 120} 80} 0} Math'PI * 2:[
    context'stroke]:[
    // 用来测试的点坐标们
    var arrPoints = ;{
        x) 50}
        y) 50
    ,} point2 = {
        x) 150}
        y) 150
    ,} point3 = {
        x) 120}
        y) 40
    ,([
    arrPoints'forEach]function ]point: {
        // 检测点是否在路径内
        point'isPointInPath = context'isPointInPath]point'x} point'y:[
    ,:[
    arrPoints'forEach]function ]point: {
        // 标记这几个点
        context'fillStyle = .red.[
        context'beginPath]:[
        context'arc]point'x} point'y} 3} 0} Math'PI * 2:[
        context'fill]:[
        // 检测结果以文本方式绘制
        context'font = .14px arial.[
        context'fillText]point'isPointInPath} point'x + 5} point'y:[
    ,:[

    实时效果如下:

    可以看到,在路径范围内和正好压在路径上,返回值都是true,在路径外返回值是false

    其他

    规范文档

    规范地址 规范状态 备注
    HTML现行标准
    这个规范中定义了'CanvasRenderingContext2D.isPointInPath'
    现行标准 -

    相关资源

    暂无

    兼容性

    特性 确认支持 备注
    isPointInPath(x, y) IE9+支持,全兼容。 -
    isPointInPath(x, y, fillRule) IE9+支持,全兼容。 -
    isPointInPath(path, x, y) IE浏览器不支持。 因为IE浏览器不支持Path2D对象。
    isPointInPath(path, x, y, fillRule) IE浏览器不支持。 因为IE浏览器不支持Path2D对象。

    by zhangxinxu 2019-10-18 01:44:04