--- title: CanvasRenderingContext2D.isPointInPath() slug: Web/API/CanvasRenderingContext2D/isPointInPath translation_of: Web/API/CanvasRenderingContext2D/isPointInPath ---
{{APIRef}}

CanvasRenderingContext2D.isPointInPath()是 Canvas 2D API 用于判断在当前路径中是否包含检测点的方法

语法

boolean ctx.isPointInPath(x, y);
boolean ctx.isPointInPath(x, y, fillRule);

boolean ctx.isPointInPath(path, x, y);
boolean ctx.isPointInPath(path, x, y, fillRule);

参数

x
检测点的X坐标
y
检测点的Y坐标
fillRule
用来决定点在路径内还是在路径外的算法。
允许的值:
path
{{domxref("Path2D")}}应用的路径。

返回值

{{jsxref("Boolean")}}
一个Boolean值,当检测点包含在当前或指定的路径内,返回 true;否则返回 false。

示例

使用 isPointInPath 方法

这是一段简单的代码片段,使用 isPointinPath 方法检查某点是否在当前的路径内。

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.rect(10, 10, 100, 100);
ctx.stroke();
console.log(ctx.isPointInPath(10, 10)); // true

修改下面的代码, 在线查看 canvas的变化并在你的 控制台 中观察日志信息:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.rect(10, 10, 100, 100);
ctx.stroke();
console.log(ctx.isPointInPath(10, 10)); // true</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", function() {
  textarea.focus();
})

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

{{ EmbedLiveSample('Playable_code', 700, 360) }}

规范描述

Specification Status Comment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-ispointinpath", "CanvasRenderingContext2D.isPointInPath")}} {{Spec2('HTML WHATWG')}}  

浏览器兼容性

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Path parameter {{ CompatVersionUnknown() }} {{ CompatGeckoDesktop(31) }} {{ CompatNo }} {{ CompatVersionUnknown() }} {{ CompatNo }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Path parameter {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatGeckoMobile(31) }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

Compatibility 注解

参见