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. CSP-S全国模拟赛第三场 【nan死了】

    mmt 居然第一步膜化乘除 都没看出来,没救了... 大概是贡献前缀和优化的做法 巨兔式讲解:大家都学会了么? 咱发现有大量的 (i/j , i%j ) 同时 对很多 c 产生了贡献,咱可以去优化这一 ...

  2. import cycle not allowed in test

    写个 sdk 的测试时报错 import cycle not allowed in test 后发现因为测试文件内多写了导入同包路径. 同 package 下的 xxx_test.go 内不需要额外 ...

  3. CentOS6.6安装使用MyCat

    https://blog.csdn.net/u012948302/article/details/78902092 1. 安装Java环境MyCAT 是使用 JAVA 语言进行编写开发,使用前需要先安 ...

  4. npm学习(八)之如何使用语义化版本

    npm的语义化版本控制——Semantic versioning 在新发布的代码中传达更改的程度非常重要,因为有时更新会破坏包需要的代码(称为依赖项).语义化版本控制(semver)是一个旨在解决这个 ...

  5. 剑指offer 剪绳子

    题目描述 给你一根长度为n的绳子,请把绳子剪成m段(m.n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],...,k[m].请问k[0]xk[1]x...xk[m]可能 ...

  6. JVM内存结构思维导图

  7. js 学习三 Array

    1.数组的长度 var sequence = [1, 1, 2, 3, 5, 8, 13]; sequence .length //7 2.字符串转换成数组 string.split() var my ...

  8. curry&unCurry函数

    unCurry函数与curry函数区别:curry化函数:固定部分参数,返回一个接受剩余参数的新函数,目的是为了缩小适用范围,创建一个针对性更强的函数. unCurry化函数:扩大适用范围,创建一个应 ...

  9. 爬虫获取网页数据,报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start by

    https://blog.csdn.net/hj_xy_0705/article/details/85011072

  10. YUV格式详解【转】

    转自:http://blog.csdn.net/searchsun/article/details/2443867 [-] YUV格式解析1播放器project2 YUV 采样 表面定义 YUV格式解 ...