简体   繁体   English

鼠标在画布上的位置

[英]Mouse position on a canvas

I am a bit confused here about how to interact with an image in a canvas. 我对如何与画布中的图像进行交互感到有些困惑。

My images load but I want to be able to click a given image and work out which image the mouse has clicked. 我的图像已加载,但我希望能够单击给定的图像并确定鼠标单击的图像。

But the images can be offset aswell which makes matters more confusing, so I was wondering if there was a some kind of mathematical way to calculate which image your mouse is over when you click the canvas? 但是图像也可以偏移,这会使事情更加混乱,所以我想知道是否存在某种数学方法来计算单击画布时鼠标悬停在哪个图像上?

Not tried in on a canvas, but maybe it can help (part is jQuery), base rely on DOM function elementFromPoint(): 没有在画布上尝试过,但是也许可以帮上忙(部分是jQuery),它基于DOM函数elementFromPoint():

getElemFromPos = function(x,y,def)
{
 var f = 'elementFromPoint',
     x=parseInt(x),y=parseInt(y),d=$j(document);
 if(!d[0][f] || isNaN(x) || isNaN(y)) return def;
 var w=$(window),bRel=0;
 if( !d[0].__ajqefpc )
 {
   var sl=d.scrollTop();
   if( sl >0)
    { bRel = (d[0][f](0, sl + w.height() -1) == null); }
   else if((sl = d.scrollLeft())>0 )
         { bIsRel = (d[0][f](sl + w.width() -1, 0) == null); }
   d[0].__ajqefpc=(sl>0);
 }

 if(!bRel)
 {
   x += d.scrollLeft();
   y += d.scrollTop();
 }

 var r = d[0][f](x,y);
 return (r && r!=null)?r:false;
};

Are you using any javascript libraries? 您在使用任何JavaScript库吗? I would suggest wrappping all your images in a div with the same class then doing something like this: 我建议将所有图像包装在同一类的div中,然后执行以下操作:

jQuery('.imageWrapper').click(function(elm){
  console.log(this , elm);
  //some code to run here
}

In this instance this should refer to the event, and elm should be the element, that you clicked on. 在这种情况下,它应该引用事件,而elm应该是您单击的元素。 You can then do whatever you need to to that element. 然后,您可以对该元素执行任何所需的操作。

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

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