CanvasRenderingContext2D: isPointInStroke() 方法
CanvasRenderingContext2D.isPointInStroke() 方法(Canvas 2D API 的一部分)用於報告指定的點是否位於路徑描邊所包含的區域內。
語法
js
isPointInStroke(x, y)
isPointInStroke(path, x, y)
引數
返回值
- 一個布林值。
-
一個布林值,如果該點位於路徑描邊所包含的區域內,則為
true,否則為false。
示例
檢查當前路徑中的點
此示例使用 isPointInStroke() 方法檢查一個點是否位於當前路徑描邊區域內。
HTML
html
<canvas id="canvas"></canvas>
<p>In stroke: <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.stroke();
result.innerText = ctx.isPointInStroke(50, 10);
結果
檢查指定路徑中的點
每當滑鼠移動時,此示例都會檢查游標是否位於一個橢圓 Path2D 路徑的描邊內。如果是,則橢圓的描邊變為綠色,否則為紅色。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI * 0.25, 0, 2 * Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = "red";
ctx.fill(ellipse);
ctx.stroke(ellipse);
// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
// Check whether point is inside ellipse's stroke
const isPointInStroke = ctx.isPointInStroke(
ellipse,
event.offsetX,
event.offsetY,
);
ctx.strokeStyle = isPointInStroke ? "green" : "red";
// Draw ellipse
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(ellipse);
ctx.stroke(ellipse);
});
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-ispointinstroke-dev |
瀏覽器相容性
載入中…
另見
- 定義此方法的介面:
CanvasRenderingContext2D