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, ' === ".

最新文章

  1. 【系统架构】IT职业技能图谱(点开大图查看)
  2. Unity3D 预设打包的注意事项
  3. netty发送utf-8编码的信息
  4. java8 ArrayList源码阅读
  5. .NET Nancy 详解(三) Respone 和 ViewEngine
  6. xmpp整理笔记:聊天信息的发送与显示
  7. 周赛-Toy Cars 分类: 比赛 2015-08-08 15:41 5人阅读 评论(0) 收藏
  8. Android udev /dev 设备节点权限
  9. pcap文件的文件头的link type
  10. JavaScript权威指南科13章 webj浏览器avascript
  11. ThoughtWorks Merchant&#39;s Guide To The Galaxy
  12. CSU 1650 影魔大战
  13. python实现多变量线性回归(Linear Regression with Multiple Variables)
  14. python 导入informixdb模块
  15. MPSOC之4——petalinux提取源码
  16. 分页之 skip(pageindex*(index-1).take(size).Tolist();
  17. 原博客地址http://blog.chinaunix.net/uid/20656672.html不再维护(10年前数百篇oracle/teradata性能优化、故障处理案例)
  18. 使用java输出helloworld
  19. java基础学习之单例设计模式学习
  20. Foundation-NSOperation-NSInvocationOperation/NSBlockOperation/NSOperationQueue

热门文章

  1. Openresrt最佳案例
  2. IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(Application.StartupPath + &quot;\\temp&quot;, 0); 报:异常来自 HRESULT:0x80040228
  3. redis 模拟jedis 操作string类型数据
  4. Laravel - 验证码(captcha)
  5. Juery入门2
  6. Codeforces1203F2. Complete the Projects (hard version) (贪心+贪心+01背包)
  7. Codeforces 919 行+列前缀和 树上记忆化搜索(树形DP)
  8. hdu 3549 网络流最大流 Ford-Fulkerson
  9. eddx
  10. etl-p