This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The CanvasRenderingContext2D.addHitRegion() method of the Canvas 2D API adds a hit region to the bitmap. This allows you to make hit detection easier, lets you route events to DOM elements, and makes it possible for users to explore the canvas without seeing it.
void ctx.addHitRegion(options);
The options argument is optional. When provided, it is an Object which can contain the following properties:
pathPath2D object describing the area of the hit region. If not provided, the current path is used.fillRule"nonzero").idparentIDcursorcursor to use when the mouse is over this region (defaults to "inherit"). Inherits the cursor of the parent hit region, if any, or the canvas element's cursor.controlnull.labelnull.rolenull.addHitRegion methodThis example demonstrates the addHitRegion() method.
<canvas id="canvas"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(event) {
if(event.region) {
alert('ouch, my eye :(');
}
});
ctx.beginPath();
ctx.arc(100, 100, 75, 0, 2 * Math.PI);
ctx.lineWidth = 5;
ctx.stroke();
// Eyes
ctx.beginPath();
ctx.arc(70, 80, 10, 0, 2 * Math.PI);
ctx.arc(130, 80, 10, 0, 2 * Math.PI);
ctx.fill();
ctx.addHitRegion({id: "eyes"});
// Mouth
ctx.beginPath();
ctx.arc(100, 110, 50, 0, Math.PI);
ctx.stroke();
Edit the code below to see your changes update live in the canvas (if you don't see the full smiley, check in the browser compatibility table, if your current browser supports hit regions already, you might need to activate a preference).
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | Yes
|
? | 30
|
No | No | No |
id
|
Yes
|
? | 30
|
No | No | No |
control
|
Yes
|
? | 30
|
No | No | No |
path
|
Yes
|
? | 39
|
No | No | No |
fillRule
|
Yes
|
? | No | No | No | No |
| other hit region options | No | ? | No | No | No | No |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | No | No | ? | 30
|
No | No | No |
id
|
No | No | ? | 30 | No | No | No |
control
|
No | No | ? | 30 | No | No | No |
path
|
No | No | ? | 30 | No | No | No |
fillRule
|
No | No | ? | No | No | No | No |
| other hit region options | No | No | ? | No | No | No | No |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/addHitRegion