How do I add a simple onClick event handler to a canvas element?
How do I add a simple onClick event handler to a canvas element?
When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.
The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.
Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.
To add a click event to your canvas element, use...
canvas.addEventListener('click', function() { }, false);
To determine what element was clicked...
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function(element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});
This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.
The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.
When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.
For completeness, why your attempts didn't work...
elem.onClick = alert("hello world"); // displays alert without clicking
This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().
elem.onClick = alert('hello world'); // displays alert without clicking
In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.
elem.onClick = "alert('hello world!')"; // does nothing, even with clicking
You are assigning a string to the onClick property of elem.
elem.onClick = function() { alert('hello world!'); }; // does nothing
JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.
elem.onClick = function() { alert("hello world!"); }; // does nothing
Again, ' === ".
How do I add a simple onClick event handler to a canvas element?的更多相关文章
- js: get event handler bound to the element
jQuery._data(jQuery(this)[0], "events" ).click[0].handler $._data( $("#myabc")[0 ...
- Add a Simple Action添加简单按钮
In this lesson, you will learn how to create a Simple Action. For this purpose, a new View Controlle ...
- Add a Simple Action using an Attribute 使用特性添加简单按钮
In the previous Add a Simple Action lesson, you learned how to add an Action by implementing the Vie ...
- Executing a script from Nagios event handler fails to run
I have Nagios running on a webserver. For this one Nagios service check in particular, if it fails, ...
- jquery , find the event handler,找到jquery中的event handler
找到 dispatch: function (e) { e = b.event.fix(e); var n, r, i, s, o, u = [], a = d.call(arguments), f ...
- Event Handler
在Event Handler中,有一种特殊的Event Handler,称之为Synchronizer或者Denormalizer,其作用就是为了同步“Query Database”.Query Da ...
- SharePoint中Event Handler的触发
一直以来对于Event Handler的感觉就是:添加.编辑和删除动作之前和动作之后,我们在SharePoint系统中可以做的一些事情 不过在最近处理的一个问题中,发现它在触发时机上出了一点问题 ...
- SSIS ->> Event Handler
Event Handler支持在某个事件触发的时候定义好处理该事件的逻辑,比如错误事件触发是该怎么处理.它跟Control Flow界面相似,就好像执行了另外一个包一样.Event Handler不仅 ...
- JPA project Change Event Handler问题解决[转]
转至:http://my.oschina.net/cimu/blog/278724 这是Eclipse中的一个GUG: Bug 386171 - JPA Java Change Event Handl ...
随机推荐
- 不用再去找rem了,你想要的rem都在这
一.兼容性. 目前,IE9+,Firefox.Chrome.Safari.Opera 的主流版本都支持了rem(大胆用吧,目前几乎所有手机浏览器都支持rem) 二.什么是rem. rem是相对于根元素 ...
- 在 sessionStorage存储json对象
目的:A页面存的东西要从B页面拿到 因为sessionStorage.setItem("key","value")内存储的都是字符串,所以,如果以对象的形式存到 ...
- case函数,replace函数
(case '字段' when '数据1' then '输出1' when '数据2' then '输出2' when '数据3' then '输出3' else '其他数据输出一致' end) as ...
- openapi
https://www.breakyizhan.com/swagger/2810.html https://www.cnblogs.com/serious1529/p/9318115.html htt ...
- 9- 基于6U VPX的 XC7VX690T+C6678的双FMC接口雷达通信处理板 C6678板卡
基于6U VPX的 XC7VX690T+C6678的双FMC接口雷达通信处理板 一.板卡概述 高性能VPX信号处理板基于标准6U VPX架构,提供两个标准FMC插槽,适用于电子对抗或雷达信号等领域 ...
- SpringCloud系列(一):Eureka 服务注册与服务发现
上一篇,我们介绍了服务注册中心,光有服务注册中心没有用,我们得发服务注册上去,得从它那边获取服务.下面我们注册一个服务到服务注册中心上去. 我们创建一个 hello-service 的 spring ...
- Codeforces 911 三循环数覆盖问题 逆序对数结论题 栈操作模拟
A #include <bits/stdc++.h> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #def ...
- 牛顿迭代法——C语言
include <stdio.h> include <math.h> int main() { flaot solution(float a,flaot b,float c,f ...
- 用 Webpack 解决应用性能问题
1. 影响页面加载时长的 Top3 因素 页面初载时,加载大量 JavaScript 脚本: 页面初载时,加载大量 CSS 文件: 页面初载时,加载大量网络资源: 页面加载的越久,页面不可交互的时间就 ...
- 移动UI控件Telerik UI for Xamarin发布R2 2019|引入Map控件
Telerik UI for Xamarin是一个构建跨平台移动应用程序的原生UI.Telerik UI for Xamarin使用Xamarin.Forms技术,它可以让开发人员从一个单一的共享C# ...