简体   繁体   English

画布中元素中的事件

[英]Events in elements within a canvas

I've draw an image inside a canvas tag. 我已经在canvas标签内绘制了图像。 How could I add events to it? 如何向其中添加事件? I want to do something when user clicks in that image. 当用户单击该图像时,我想做些事情。

character.addEventListener('click', function() { alert('foo'); }, true);
/* character is a var (image object) within a canvas */

Thank you. 谢谢。

get click event of each rectangle inside canvas? 获取画布内每个矩形的点击事件?

Further more, I have found that this answer does not work in Mozilla. 此外,我发现此答案在Mozilla中不起作用。

Instead use clientX instead of offsetX. 而是使用clientX而不是offsetX。

Example, I have created a dynamic canvas image gallery on github at: https://github.com/michaelBenin/fi-test 例如,我在github上的以下位置创建了一个动态画布图像画廊: https : //github.com/michaelBenin/fi-test

Every time the window is resized I recalculate the x, y, of each image drawn, from there I run the collisions function when the canvas is clicked. 每次调整窗口大小时,我都会重新计算绘制的每个图像的x,y,然后在单击画布时从那里运行碰撞函数。

Basically you get the x, y value from the click event and check to see if there is anything on the canvas at those coordinates. 基本上,您可以从click事件中获取x,y值,并检查画布上这些坐标处是否有任何东西。

Here is another good link on registering click events inside of canvas: http://eli.thegreenplace.net/2010/02/13/finding-out-the-mouse-click-position-on-a-canvas-with-javascript/ 这是在画布内注册单击事件的另一个很好的链接: http : //eli.thegreenplace.net/2010/02/13/finding-out-the-mouse-click-position-on-a-canvas-with-javascript /

There's no way to add event handlers to actual drawings on the canvas. 无法将事件处理程序添加到画布上的实际图形中。 You can handle events for the entire canvas - that's it. 您可以处理整个画布的事件-就是这样。

Your options at this point is to either add an abstraction over the canvas, and lookup drawings you have there based on coordinates from canvas click events - or to drop canvas altogether and go for eg svg. 此时,您的选择是在画布上添加一个抽象,然后基于画布单击事件中的坐标查找在其中具有的绘图-或完全放下画布并使用svg。 The Raphaël library (http://raphaeljs.com/) can help you with the latter. Raphaël库(http://raphaeljs.com/)可以为您提供帮助。

See blow link,there is a sample 见吹链接,有一个样本

http://www.html5canvastutorials.com/cookbook/ch6/1369_06_03/ http://www.html5canvastutorials.com/cookbook/ch6/1369_06_03/

See the source of page 查看页面来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM