CanvasRenderingContext2D: isPointInPath() 方法
CanvasRenderingContext2D.isPointInPath() 方法是 Canvas 2D API 的一部分,用於報告指定的點是否包含在當前路徑中。
語法
js
isPointInPath(x, y)
isPointInPath(x, y, fillRule)
isPointInPath(path, x, y)
isPointInPath(path, x, y, fillRule)
引數
返回值
- 一個布林值。
-
一個布林值,如果指定的點包含在當前或指定的路徑中,則為
true,否則為false。
示例
檢查當前路徑中的點
此示例使用 isPointInPath() 方法來檢查一個點是否在當前路徑內。
HTML
html
<canvas id="canvas"></canvas>
<p>In path: <code id="result">false</code></p>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const result = document.getElementById("result");
ctx.rect(10, 10, 100, 100);
ctx.fill();
result.innerText = ctx.isPointInPath(30, 70);
結果
檢查指定路徑中的點
每當您移動滑鼠時,此示例都會檢查游標是否在一個圓形的 Path2D 路徑中。如果是,圓圈會變綠,否則會變紅。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Create circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill(circle);
// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
// Check whether point is inside circle
const isPointInPath = ctx.isPointInPath(circle, event.offsetX, event.offsetY);
ctx.fillStyle = isPointInPath ? "green" : "red";
// Draw circle
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(circle);
});
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-ispointinpath-dev |
瀏覽器相容性
載入中…
Gecko 特有說明
- 在 Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) 之前,此方法錯誤地未能將指定點的座標乘以當前變換矩陣,然後與路徑進行比較。現在,即使上下文被旋轉、縮放或以其他方式變換,此方法也能正常工作。
另見
- 定義此方法的介面:
CanvasRenderingContext2D