简体   繁体   English

将事件侦听器添加到html5画布上的绘制对象

[英]Add an event listener to a drawn object on html5 canvas

I'm making a game where the bubbles (circles) appear on the screen and move upwards and I'm using HTML5 and JavaScript only which means no frameworks like kinetic and no jQuery at all. 我正在制作一个游戏,其中气泡(圆圈)出现在屏幕上并向上移动,并且我仅使用HTML5和JavaScript,这意味着根本没有像动力学这样的框架,也没有jQuery。

I've come to a point where I want to add an event listener to the bubble itself, now I understand that because the bubble is an object on the canvas, it has no method 'addEventListener' so I can't directly add a click event to the bubble, I was wondering if anybody could help me with this problem I'm having? 我已经到了要向气泡本身添加事件侦听器的地步,现在我了解到,由于气泡是画布上的对象,因此它没有方法“ addEventListener”,因此我无法直接添加点击事件到泡沫中,我想知道是否有人可以帮助我解决这个问题? Here is a fiddle of what happens so far... 这是到目前为止发生的事情的一个小提琴...

Bubbles 泡泡

I have tried to add the event listener to the bubble as specified before by doing this... 我试图通过这样做将事件侦听器添加到之前指定的气泡中...

bubbles[i].addEventListener('click', function);

I have also tried adding mouseevents such as 我也尝试添加鼠标事件,例如

bubbles[i].onmouseenter = function () { console.log("blah") }

But now, I'm seriously at a loss 但是现在,我很茫然

Thanks in advance! 提前致谢!

I have updated your sample on jsfiddle demonstrating hit-testing. 我已经更新了有关jsfiddle示例,以演示命中测试。 This sample uses an onmousemove event handler bound to the canvas and performs the actual hit-test when this event occurs. 此示例使用绑定到画布的onmousemove事件处理程序,并在发生此事件时执行实际的命中测试。 The hit-test in your case is "Is the mouse coordinate with in the bubble's circle?" 在您的情况下,命中测试是“鼠标是否在气泡的圆圈中与之协调?”

Summary of changes: 变更摘要:

  • A "bubble" has a color property to demonstrate the effect of a hit test. “气泡”具有颜色特性,可以证明命中测试的效果。
  • function hitTest(x, y) { ... } used to test whether the passed in coordinates are within the bubble. function hitTest(x, y) { ... }用于测试传入的坐标是否在气泡内。
  • function getMouse(e, canvas) ... used to transform the mouse coordinates to canvas relative coordinates. function getMouse(e, canvas) ...用于将鼠标坐标转换为画布相对坐标。 ie, the mouse coordinate needs to be relative to the upper left hand corner of the canvas to be accurate. 也就是说,鼠标坐标必须相对于画布的左上角才能准确。

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

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