HTML5 canvas Mouseover事件 [英] HTML5 canvas Mouseover event

查看:108
本文介绍了HTML5 canvas Mouseover事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将鼠标悬停或任何事件绑定到画布上的绘制对象?例如,我试过这个:

How do I bind a mouseover or any event for that matter to a drawn object on the canvas? For instance, I tried this:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();

//STEP ONE
var stepOneRec = ctx.rect(20, 60, 266, 50);
ctx.stroke();
stepOneRec.addEventListener("mouseover", function() { alert('it works!'); });

在一个网站上,我看到它显示了一个使用Kinetic.js的方法。如果这是唯一的方法,我将使用它,我只是假设有一种方法将事件绑定到绘制的元素而无需额外的插件。对不起Canvas noob。我在这里编写了一个代码: http://jsfiddle.net/jyBSZ/2/ / p>

On one site I looked at it showed a method using Kinetic.js. If that's the only way, I'll use it, I just assume that there's a way to bind events to drawn elements without extra plug-ins. Sorry Canvas noob. I made a fiddle with my code here: http://jsfiddle.net/jyBSZ/2/

推荐答案

(我将其作为发布的评论开始,然后意识到这是一个真正的答案。)

(I started this as a posted comment, then realized it's an actual answer.)

不幸的是,在它自己的javascript中,你不能。没有画布对象,只有画布作为一个整体,以及你在其上下文中提取的内容。像kinetic这样的插件可以为你创建对象,但是画布的全部意义在于浏览器可以将其视为单个静态图像。

Unfortunately, in javascript on it's own, you can't. There are no canvas objects, just the canvas as a whole, and whatever you drew on to its context. Plugins like kinetic can make objects for you, but the whole point of canvas is that the browser can think of it as a single static image.

如果你愿意,你可以将mousemove事件绑定到画布上,跟踪它的位置和你绘制内容的位置,并暗示你自己已经结束了那个对象(实际上是插件的作用),但它是单个画布上的所有mousemove事件,而不是鼠标移动事件的组件。 (您甚至可以使事件绑定模拟对象的鼠标悬停事件,但在下面,它仍然基于检查移动并检查您自己的对象设置。)

If you want to, you can bind mousemove events to the canvas, track its position and the position where you drew stuff, and imply on your own that it's over "that object" (effectively what the plugins do), but it's all mousemove events on a single canvas rather than mouseover events on components of it. (You could even make your event binding simulate a mouseover event for the "objects", but underneath, it's still based on checking movement and checking your own object setup.)

这篇关于HTML5 canvas Mouseover事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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