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. luoguP3261_[JLOI2015]城池攻占

    题意 有一棵树\(n\)个节点,每个节点有一个防御值,以及两个属性,表示一个骑士占领该节点后攻击值是加还是乘,有\(m\)个骑士,有初始位置和初始攻击值,如果攻击值大于该节点的防御值,就能占领该节点, ...

  2. MVVM框架简单实现

    众所周知当下是MVVM盛行的时代,从早期的Angular到现在的React和Vue,再从最初的三分天下到现在的两虎相争. 无疑不给我们的开发带来了一种前所未有的新体验,告别了操作DOM的思维,换上了数 ...

  3. python操作redis用法详解

    python操作redis用法详解 转载地址 1.redis连接 redis提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用 ...

  4. Redis的频道发布与消息订阅

    Redis的频道发布与消息订阅 官网介绍 进程间的一种通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. 订阅/发布消息图 下图展示了频道channel1,以及订阅这个频道的三个客户端-c ...

  5. 初探CSS - 5 创建

    CSS 创建 当读到一个样式表时,浏览器会根据它来格式化 HTML 文档. 如何插入样式表 插入样式表的方法有三种: 外部样式表(External style sheet) 内部样式表(Interna ...

  6. Git 操作 GitHub

    Git安装 https://www.cnblogs.com/taopanfeng/p/11076702.html 设置用户名(设置一次 以后就不用再设置了) git config --global u ...

  7. java 求数组最大子序列之和

    经典问题: 给定一个int[]数组,求其最大子序列之和(条件:数组中不全部都是负数). 最优算法,线性时间复杂度: public static int maxSubSum(int[] a){ int ...

  8. ldd - 显示共享库的依赖情况

    总览 (SYNOPSIS) ldd [-vVdr] program ... 描述 (DESCRIPTION) ldd 显示 每个 程序 需要 的 共享库 (shared library), 程序名 在 ...

  9. vue修改富文本中的元素样式

    富文本编辑器目前应用很广泛,而有时候我们想要对其中的一些元素的样式进行修改,就会遇到问题. 首先,直接修改是不可行的,因为是用v-html标签进行渲染的,无法直接获取到. 在修改的时候,一般是按标签进 ...

  10. java课堂动手测试

    课堂实验3 一个Java类文件中真的只能有一个公有类吗? 经过测试,当含有两个public  类时会报错,不能执行,假如删除第二个public则可以正常生成,说明一个java文件只能有一个公有类. 课 ...