
Attaching Event Handlers to Canvas Elements
When drawing on a canvas element, the rendered shapes lack inherent representation beyond their pixels. This means that click events cannot be attached directly to individual shapes.
Solution:
To add a click handler to a canvas element:
1 | canvas.addEventListener( 'click' , function () { }, false);
|
Copy after login
To determine which element within the canvas was clicked:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var canvas = document.getElementById( 'myCanvas' );
var canvasLeft = canvas.offsetLeft + canvas.clientLeft;
var canvasTop = canvas.offsetTop + canvas.clientTop;
var context = canvas.getContext( '2d' );
var elements = [];
canvas.addEventListener( 'click' , function (event) {
var x = event.pageX - canvasLeft;
var y = event.pageY - canvasTop;
elements.forEach( function (element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert( 'Clicked an element' );
}
});
}, false);
|
Copy after login
Failed Attempts:
-
elem.onClick = alert("hello world");: Assigns the return value of alert() to the onClick property, immediately displaying the alert.
-
elem.onClick = "alert('hello world!')";: Assigns a string to the onClick property, resulting in no event handling.
-
elem.onClick = function() { ... }: Uses the archaic method of event handling, which is case-sensitive (onclick vs. onClick).
The above is the detailed content of How to Attach Event Handlers to Canvas Elements and Detect Clicks on Shapes?. For more information, please follow other related articles on the PHP Chinese website!