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 ...
随机推荐
- wex5 如何导包
wex5中 导jar包 要先把jar文件放在: E:\WeX5\runtime\BaasServer\WEB-INF\lib目录中(我wex5放的是E盘) 点击项目 --> 属性 --> ...
- react中父组件给子组件传值
子组件 state = { msg: 'a' } render(){ return<h1>{this.state.msg}</h1> } setInfo = (val)=> ...
- vue学习【番外篇】vue-cli脚手架的安装
大家好,我是一叶,今天和大家分享的是vue-cli脚手架的安装,关于vue-cli的优点,我就不赘述了. 一.检查安装node 安装vue-cli之前,先检查node是否安装.win+R,输入cmd打 ...
- 基于zynq XC7Z100 FMC接口通用计算平台 XC7Z100
一.板卡概述 本板卡基于Xilinx公司的FPGA XC7Z100 FFG 9000 芯片, 该平台为设计和验证应用程序提供了一个完整的开发平台.该平台使设计师能够更加简单进行高性能的原型设计,并 ...
- MATLAB中产生高斯白噪声的两个函数
MATLAB中产生高斯白噪声非常方便,可以直接应用两个函数,一个是WGN,另一个是AWGN.WGN用于产生高斯白噪声,AWGN则用于在某一信号中加入高斯白噪声.1.WGN:产生高斯白噪声 y = wg ...
- Vue Cli 移动端开发
一.
- Rsync实现负载均衡的数据同步
使用三台服务器:系统:CentOS 6.8 192.168.8.169 开发服务器 192.168.8.167 线上服务器1192.168.8.168 线上服务器2 实现思路:在开发服务器上制定一个规 ...
- ZROI 19.08.11模拟赛
传送门 写在前面:为了保护正睿题目版权,这里不放题面,只写题解. dlstql,wsl A \(10pts:\) \(a=100,T=100\),对每个排列构造一个反的,一步到位即可. \(20pts ...
- webpack命令:Module build failed(from ./node_modules/babel-loader/lib/index.js)/405/错误解决
在项目中运行的时候出现报错,错误为Module build failed (from ./node_modules/babel-loader/lib/index.js) 解决方案: 控制台输入 np ...
- Django ckeditor增加编辑代码 功能
前言 使用ckeditor这个组件的时候 对于长写博客的同学当然希望能有 增加代码这个功能按钮 而这个按钮 需要自己配置 我们的编辑器自然需要添加代码块的功能. 需要用到插件codesnippet,c ...