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 ...
随机推荐
- c#服务端图片打包下载
一,设计多图片打包下载逻辑:1,如果是要拉取腾讯云等资源服务器的图片,2,我们先把远程图片拉取到本地的临时文件夹,3,然后压缩临时文件夹,4,压缩完删除临时文件夹,5,返回压缩完给用户,6,用户就去请 ...
- CTP报单参数详解
交易所代码 产品类型 业务类型 价格类型 指令类型 价格类型 OrderPriceType 有效期类型 TimeCondition 成交量类型 VolumeCondition 备注 CZCE 郑商所 ...
- linux下重启tomcat命令
在Linux系统下,重启Tomcat使用命令操作的! 首先,进入Tomcat下的bin目录 cd /usr/local/tomcat/bin 使用Tomcat关闭命令 ./shutdown.sh 查看 ...
- Delphi 数据类型
- Delphi 源代码生成器
- 设备树里面#address-cells 、#size-cells、reg三者的关系
栗子1: cpus { #address-cells = <>; #size-cells = <>; cpu@ { compatible = "arm,cortex- ...
- Saving Tang Monk II HihoCoder - 1828 2018北京赛站网络赛A题
<Journey to the West>(also <Monkey>) is one of the Four Great Classical Novels of Chines ...
- JAVA并发编程的艺术 Java并发容器和框架
ConcurrentHashMap ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成. 一个ConcurrentHashMap里包含一个Segment数组, ...
- html中全选反选
<!--第一层--> <div class="first"> <div class="first_top"> <img ...
- 动态树(Link-Cut-Tree)简单总结(指针版本)
Link-Cut-Tree(动态树 LCT) 1.定义 1. 偏爱子节点: 一颗子树内最后访问的点若在该子树根节点 X 的某个儿子节点 P 的子树中,则称 P 为 X 的偏爱子节点. 偏爱边:连向偏爱 ...