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. webelement类的方法

    webelement类的方法,常用的汇总如下: clear()清空 例如登录时先清空输入框中的内容 driver.find_element_by_id('username').clear() clic ...

  2. wyy Downloader(当前置顶项目)

    第一个大刀阔斧肝的 PY 项目,名称简称为 wyyDLer 公开 EXE 计划: 感觉程序应该是没什么可以完善的了,然后就顶雷([雾 ) 把 EXE 放上来好了 1.2版下载链接 应该不会出事把 Qv ...

  3. pgsql物理复制(pgsql 备库的搭建以及角色互换,提升)

    结构图如下: Postgresql早在9.0版本开始支持物理复制,也称为流复制,通过从实例级复制出一个与主库一模一样的备库.流复制同步方式有同步,异步两种,如果主节点和备节点不是很忙,通常异步模式下备 ...

  4. 如何把maven文件pom.xml中的java包下载下来

    右击pom.xml文件,选择Run As-->Maven build- 在打开的页面中,如图输入"dependency:copy-dependencies",后点击" ...

  5. this 到底指向谁

    this 的指向,是在调用函数时根据执行上下文所动态确定的. 在函数体中,简单调用该函数时(非显式/隐式绑定下),严格模式下 this 绑定到 undefined,否则绑定到全局对象 window/g ...

  6. h5与app混合开发,jsbridge

    https://juejin.im/post/5bda6f276fb9a0226d18931f https://juejin.im/post/5abca877f265da238155b6bc http ...

  7. C++循环单链表删除连续相邻重复值

    比如:1(头)->2->2->3->3->1->1(头) 去除以后的结果是1->2->3,注意头尾的1也要去掉一个. #include "st ...

  8. Maven项目构建利器05——Maven的生命周期

    Maven各个构建环节执行的顺序: 不能打乱顺序, 必须按照既定的正确顺序(编译,测试.打包.部署)来执行Maven的核心程序中定义了抽象的生命周期, 生命周期中各个阶段的具体任务是由插件来完成的,可 ...

  9. 微信小程序自定义字体及自定义图标问题说明

    自定义图标及自定义字体,一直是很多小程序开发者的心病,其实本站是很多解决方案的,为了集中起来,方便直接跳过此坑,我特别做了这次针对字体及字体图标的跳坑: 相关文章:微信小程序添加并使用外部字体(成功添 ...

  10. faiss的简单使用

    简介 faiss是为稠密向量提供高效相似度搜索和聚类的框架.由Facebook AI Research研发. 具有以下特性. 1.提供多种检索方法 2.速度快 3.可存在内存和磁盘中 4.C++实现, ...