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);
});​

jsFiddle.

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?的更多相关文章

  1. js: get event handler bound to the element

    jQuery._data(jQuery(this)[0], "events" ).click[0].handler $._data( $("#myabc")[0 ...

  2. Add a Simple Action添加简单按钮

    In this lesson, you will learn how to create a Simple Action. For this purpose, a new View Controlle ...

  3. 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 ...

  4. 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, ...

  5. 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 ...

  6. Event Handler

    在Event Handler中,有一种特殊的Event Handler,称之为Synchronizer或者Denormalizer,其作用就是为了同步“Query Database”.Query Da ...

  7. SharePoint中Event Handler的触发

    一直以来对于Event Handler的感觉就是:添加.编辑和删除动作之前和动作之后,我们在SharePoint系统中可以做的一些事情 不过在最近处理的一个问题中,发现它在触发时机上出了一点问题   ...

  8. SSIS ->> Event Handler

    Event Handler支持在某个事件触发的时候定义好处理该事件的逻辑,比如错误事件触发是该怎么处理.它跟Control Flow界面相似,就好像执行了另外一个包一样.Event Handler不仅 ...

  9. JPA project Change Event Handler问题解决[转]

    转至:http://my.oschina.net/cimu/blog/278724 这是Eclipse中的一个GUG: Bug 386171 - JPA Java Change Event Handl ...

随机推荐

  1. Linux五大网络IO模型图解

    对于一个应用程序即一个操作系统进程来说,它既有内核空间(与其他进程共享),也有用户空间(进程私有),它们都是处于虚拟地址空间中.用户进程是无法访问内核空间的,它只能访问用户空间,通过用户空间去内核空间 ...

  2. ubuntu下搭建车场环境(代码使用jekins构建)

    1.安装jdk,jre sudo apt-get update # 更新软件包管理器,如果已经执行过,则可以不用再执行 sudo apt-get install default-jdk # 安装默认的 ...

  3. LNMP完整安装教程

    软件下载地址   https://lnmp.org/install.html 本环境与外网生产环境一致(MySQL 5.6 + PHP 7.1 + CentOS + Nginx 1.12 ) 上图红色 ...

  4. The authenticity of host 'github.com (52.74.223.119)' can't be established.

    出现这种错误的问题应考虑是否配置ssh,若没有配置,则进行相关配置 若配置后还出现这种问题,这是由于本地缺少一个文化夹.直接yes而不是y或是回车

  5. python字符串/列表/字典互相转换

    python字符串/列表/字典互相转换 目录 字符串与列表 字符串与字典 列表与字典 字符串与列表 字符串转列表 1.整体转换 str1 = 'hello world' print(str1.spli ...

  6. Apple历史应用以及开发工具版本(Xcode官方历史版本等等)

    1.Xcode 官方历史版本下载:(需要登录开发者账号) https://developer.apple.com/download/more/

  7. 修改docker自定义网桥后的默认网卡名称

    [root@docker2 ~]# docker  network   create  --subnet=10.10.10.0/24  docker1   #新键网桥docker142323044a4 ...

  8. CentOS7+ 普通用户使用密钥登陆服务器(同时禁用root登陆)

    创建普通用户: # useradd user01 # tail -n2 /etc/passwd chrony:x:998:996::/var/lib/chrony:/sbin/nologin user ...

  9. 005-监控项item详解,手动创建item实例

    模板里的监控项都可以用 zabbix-get 命令执行 来获取相应的值,方法如下: [root@linux-node2 ~]# zabbix_get -s 192.168.1.230 -k agent ...

  10. python中对RSA的加密和解密

    首先,生成一对密钥,并保存 def create_keys(): # 生成公钥和私钥 (pubkey, privkey) = rsa.newkeys(1024) pub = pubkey.save_p ...