在html5画布上为绘制的对象添加事件侦听器 [英] Add an event listener to a drawn object on html5 canvas

查看:167
本文介绍了在html5画布上为绘制的对象添加事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个游戏,其中气泡(圆圈)出现在屏幕上并向上移动,我只使用HTML5和JavaScript,这意味着没有像kinetic和jQuery这样的框架。

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.

我已经到了一个点,我想在泡泡本身添加一个事件监听器,现在我明白了,因为泡泡是画布上的一个对象,它没有方法'addEventListener'所以我无法直接在泡泡中添加点击事件,我想知道是否有人可以帮助我解决这个问题?以下是到目前为止发生的事情的小提琴......

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? 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") }

但现在,我真的很亏本

提前致谢!

推荐答案

我已更新您的 jsfiddle上的示例演示命中测试。此示例使用绑定到画布的onmousemove事件处理程序,并在发生此事件时执行实际的命中测试。你的情况下的热门测试是鼠标是否在气泡的圆圈内协调?

I have updated your sample on jsfiddle demonstrating hit-testing. This sample uses an onmousemove event handler bound to the canvas and performs the actual hit-test when this event occurs. The hit-test in your case is "Is the mouse coordinate with in the bubble's circle?"

变化摘要:


  • 气泡具有颜色属性,用于演示命中测试的效果。

  • function hitTest(x, y){...} 用于测试传入的坐标是否在气泡内。

  • function getMouse(e,canvas )... 用于将鼠标坐标转换为画布相对坐标。即,鼠标坐标需要相对于画布的左上角是准确的。

  • 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 getMouse(e, canvas) ... used to transform the mouse coordinates to canvas relative coordinates. i.e, the mouse coordinate needs to be relative to the upper left hand corner of the canvas to be accurate.

这篇关于在html5画布上为绘制的对象添加事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆