Categories
JavaScript Answers

How to add a simple onClick event handler to a canvas element with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *