The CanvasRenderingContext2D.isPointInPath()
method of the Canvas 2D API reports whether or not the specified point is contained in the current path.
The CanvasRenderingContext2D.isPointInPath()
method of the Canvas 2D API reports whether or not the specified point is contained in the current path.
js
isPointInPath(x, y) isPointInPath(x, y, fillRule) isPointInPath(path, x, y) isPointInPath(path, x, y, fillRule)
x
The x-axis coordinate of the point to check, unaffected by the current transformation of the context.
y
The y-axis coordinate of the point to check, unaffected by the current transformation of the context.
fillRule
The algorithm by which to determine if a point is inside or outside the path. Possible values:
nonzero
The non-zero winding rule. Default rule.
evenodd
path
A Path2D
path to check against. If unspecified, the current path is used.
A Boolean, which is true
if the specified point is contained in the current or specified path, otherwise false
.
This example uses the isPointInPath()
method to check if a point is within the current path.
html
<canvas id="canvas"></canvas> <p>In path: <code id="result">false</code></p>
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);
Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D
path. If yes, the circle becomes green, otherwise it is red.
html
<canvas id="canvas"></canvas>
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); });
Specification |
---|
HTML Standard # dom-context-2d-ispointinpath-dev |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
isPointInPath |
1 | 12 | 2 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
path_parameter |
36 | 14 | 31 | No | 23 | 7 | 37 | 36 | 31 | 24 | 7 | 3.0 |
CanvasRenderingContext2D
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath