How do I add a simple onClick event handler to an HTML5 canvas element?

HTMLWeb DevelopmentFront End Technology

The elements that are drawn in canvas element have no representation. Their only representation is the pixels they use and their color. Drawing to a canvas element means drawing a bitmap in immediate mode. To get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and determine which element was clicked. This requires storing the element’s width and height.

To add a click event to your canvas element, use the below-given code

canvas.addEventListener('click', function() { }, false);


To determine what element was clicked, use the following code snippet −

var e = document.getElementById('myCanvas'),
   elemLeft = e.offsetLeft,
   elemTop = e.offsetTop,
   context = e.getContext('2d'),
   elements = [];

// event listener for click event
e.addEventListener('click', function(event) {
   var xVal = event.pageX - elemLeft,
   yVal = event.pageY - elemTop;
   console.log(xVal, yVal);
   elements.forEach(function(ele) {
      if (yVal > && yVal < + ele.height && xVal > ele.left && xVal < ele.left + ele.width) {
         alert(‘element clicked');
}, false);
   colour: '#1C2128’,
   width: 250,
   height: 200,
   top: 30,
   left: 20
elements.forEach(function(ele) {
   context.fillStyle = element.colour;
   context.fillRect(ele.left,, ele.width, ele.height);
Published on 20-Mar-2018 11:11:49