将鼠标悬停事件附加到多个画布图像
我有这样的代码:
$('#whatever .item').each(function() {
var canvas = document.getElementById('whatever');
var ctx = canvas.getContext('2d');
/* Drawing */
$(document).mousemove(function(e) {
mouseY = e.pageY;
mouseX = e.pageX;
if(ctx.isPointInPath(mouseX, mouseY)) {
alert("HEY!");
}
});
});
我在画布中有多个跨度标签。然后,我使用 span 标签在画布上创建图像,使用“each”。所以我假设如果我添加一个 mousemove,它会为每个 span 标签添加一个 mousemove,但事实并非如此。有什么想法吗?
I have this code:
$('#whatever .item').each(function() {
var canvas = document.getElementById('whatever');
var ctx = canvas.getContext('2d');
/* Drawing */
$(document).mousemove(function(e) {
mouseY = e.pageY;
mouseX = e.pageX;
if(ctx.isPointInPath(mouseX, mouseY)) {
alert("HEY!");
}
});
});
I have multiple span tags in the canvas. I'm then using the span tags to create images on a canvas, using 'each'. So I assumed if I added a mousemove it would add one for each span tag, but it doesn't. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我对你的理解是正确的(也许不是),你就不能像现在这样做事。
现在,
标记内有多个
标记,它们表示绘制到画布上的数据。然后,当您将鼠标悬停在绘制到画布上的数据上时,您希望发生一些事情。
这不是画布的工作原理。这些
标签都不会显示在页面上(除了作为后备内容),并且它们的 mousemove/etc 事件对画布表面没有影响。
当您使用 span 标签将图像(或任何数据)绘制到画布上时,您必须跟踪绘制它们的位置。然后,您只需要
本身上的一个
mousemove
事件,该事件将循环遍历您尝试检测的位置(或路径或矩形)列表。因此,要将鼠标事件附加到画布上绘制的图像,您必须跟踪自己绘制的所有内容。除画布本身之外的任何内容上的鼠标事件都不会削减它。所有这些都必须您自己编写或使用库。您已经表示您不想再使用库,因此这里有一个学习教程如何使画布具有交互性(鼠标按下、鼠标移动、跟踪绘制的内容等)。
If I understand you correctly, and I might not, you can't do things the way you are now.
Right now you have multiple
<span>
tags inside of a<canvas>
tag that represent data that is being drawn to the canvas. You then want something to happen when you hover over that data that is being drawn to the canvas.This is not how canvas works. None of those
<span>
tags show up on the page (except as fallback content) and their mousemove/etc events have no bearing on the canvas surface.When you use your span tags to draw images (or whatever data) to the canvas you have to keep track of where you draw them. Then you need only one
mousemove
event, on the<canvas>
itself, that will loop through the list of locations (or paths or rectangles) that you are trying to detect.So to attach a mouse event to images drawn on a canvas, you have to keep track of everything drawn yourself. Mouse events on anything except the Canvas itself won't cut it. All of this you have to write yourself or else use a library. You have indicated that you don't want to use anymore libraries so here's a tutorial on learning how to make the canvas interactive (mousedown, mousemove, keeping track of what is drawn, etc).
尝试使用 KineticJS 库。 http://www.html5canvastutorials.com/kineticjs/html5-canvas-path-鼠标悬停/
Try using KineticJS library. http://www.html5canvastutorials.com/kineticjs/html5-canvas-path-mouseover/
像这样将
mousemouse()
附加到所有图像不是更容易吗:Isn't it easier to attach the
mousemouse()
to all the images like this: