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 ...
随机推荐
- 在Asp.net core使用配置Json创建动态目录树
一.前言 使用动态目录树可以使左边栏中的目录更加灵活,本文介绍如何将目录保存在json配置文件中,再读取出来经过处理后生成目录树. 二.数据结构 1. TreeMenuNode类名 将TreeMenu ...
- IDEA配置远程git仓库
一,在项目创建本地仓储 2,选择当前文件夹为本地仓储 3, 将代码添加到本地仓库 4,提交到本地仓库 5,提交到本地仓库 配置远程账号和地址 输入你自己的远程仓库----码云或者github,创建的 ...
- 04.AutoMapper 之投影(Projection)
https://www.jianshu.com/p/031553705417 投影(Projection) 投影将源转换为目标而不是扁平化对象模型.如果没有额为的配置AutoMapper需要一个扁平化 ...
- qtdebug和release加载不同的文件配置
win32:CONFIG(release, debug|release): { LIBS +=$$PWD/../../../thirdparty\qwt\lib\qwt.lib LIBS +=$$PW ...
- 使用git配置ssh的文章推荐
https://blog.51cto.com/sgk2011/1925922 https://www.cnblogs.com/superGG1990/p/6844952.html https://bl ...
- 利用ARouter实现组件间通信,解决子模块调用主模块问题
如果你还没使用过ARouter请你按照这篇下面博客尝试使用下然后再往下看组件通信的内容(不然的话可能会懵逼)Android Studio接入ARouter以及简单使用 如果你使用过ARouter请继续 ...
- keymaps - 对键盘映射文件的描述
描述 (DESCRIPTION) loadkeys(1) 能够 通过 调入 指定的 文件 修改 键盘翻译表, 键盘翻译表 通常 用于 内核的 键盘驱动程序; 另外 dumpkeys(1) 可以 根据 ...
- Pythoy修炼之路
路漫漫其修远兮,吾将上下而求索... 编程语言众多,徘徊在C.C#.Java.PHP等十字路口,看到哪个领域大牛的成功,便想打开那扇窗,反反复复,犹豫不决,终无所获. 个人认为选择一门语言,要根据自身 ...
- c语言数组那些骚事儿
找出最大和第二大值#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { , , ...
- TF-epoch、 iteration和batchsize区别(转载)
from http://www.cnblogs.com/qggg/p/6876942.html 转自 http://blog.csdn.net/sinat_30071459/article/detai ...