![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I add a simple onClick event handler to an HTML5 canvas element?
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);
Example
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 > ele.top && yVal < ele.top + ele.height && xVal > ele.left && xVal < ele.left + ele.width) { alert(‘element clicked'); } }); }, false); elements.push({ colour: '#1C2128’, width: 250, height: 200, top: 30, left: 20 }); elements.forEach(function(ele) { context.fillStyle = element.colour; context.fillRect(ele.left, ele.top, ele.width, ele.height); });
Advertisements