To add a simple onClick event handler to a canvas element with JavaScript, we set the canvas’ onclick
property to the click handler.
For instance, we write
const elem = document.getElementById("myCanvas");
elem.onclick = () => {
console.log("hello world");
};
to select the canvas with getElementById
.
And then we set its onclick
property to a function that logs 'hello world'
.
As a result, when we click on the canvas, we see 'hello world'
. logged.