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 ...
随机推荐
- 2.学习Application
2学习Application Application对象事件 名称 说明 Activated 当应用程序成为前台应用程序时触发 Deactivated 当应用程序不再是前台应用程序时触发 Dispat ...
- java学习笔记(5)多线程
一.简介(过段时间再写,多线程难度有点大) --------------------------------------- 1.进程:运行时的概念,运行的应用程序 2.线程:应用程序内部并发执行的代码 ...
- vue-nuxt--切换布局文件
1.暂时没有找到服务器端渲染 非服务器端切换: window.$nuxt.setLayout('blog')
- Android 一共有多少种动画?准确告诉你!
Android 动画 Android 动画在开发中是不可或缺的功能,或者说是界面灵动的添加剂.那你是否总结过 Android 中总共为开发者提供了多少种方式的动画呢?今天就为大家总结归纳一下. 报 ...
- Malloc与Free不调用构造函数与析构函数
例子: #include "stdafx.h" #include <new> #include <iostream> using namespace std ...
- SpringBoot页面展示Thymeleaf
https://www.jianshu.com/p/a842e5b5012e 开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了.Spring ...
- VIM如何自动保存文件、自动重加载文件、自动刷新显示文件
1.手动重加载文件的命令是:e! 2.一劳永逸的方法是:vim提供了自动加载的选项 autoread,默认关闭. 在vimrc中添加 set autoread即可打开自动加载选项,相关选项: :hel ...
- linux下mysql5.7的MHA高可用架构搭建
一.MHA简介 MHA(Master High Availability)目前在mysql高可用方面比较成熟.是一套优秀的作为 mysql高可用性环境下故障切换和主从提升的高可用软件.在MySQL故障 ...
- java数据结构复习01
1.数组 package javaDataStruct.array01; public class MyArray { private int[] arr; // 表示有效数据的长度 private ...
- BFPRT: O(n)最坏时间复杂度找第K大问题
同时找到最大值与最小值 找到n个元素中的最大/小值,比较次数为n-1, 找到n个元素中的最大值和最小值,可以Two Pass,比较次数为2n-2 也可以One Pass,比较次数至多为\(\left ...