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, ' === "
.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-07-02 Create the Project
2015-07-02 C#中的AssemblyInfo 程序集信息
2015-07-02 Application.CommonAppDataPath的路径
2015-07-02 Factorial