

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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); });
- Related Questions & Answers
- How to add an event handler to an element in JavaScript HTML DOM?
- How to add an event handler to the specified element in JavaScript?
- HTML5 / JS storage event handler
- How do I make a transparent canvas in HTML5?
- How do I add a simple jQuery script to WordPress?
- Print a HTML5 canvas element
- How to call a JavaScript function from an onClick event?
- How do I add an element to an array list in Java?
- How can I alter the color of an HTML5 canvas element using jQuery?
- How can I use the HTML5 canvas element in IE?
- How to use multiple click event on HTML5 canvas?
- How can I get onclick event on webview in Android?
- Measure text height on an HTML5 canvas element
- HTML onclick Event Attribute
- How do I add a class to a given element using Javascript?
Advertisements