1

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?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Sir
  • 8,135
  • 17
  • 83
  • 146
  • Since images are basically rectangles, [this answer](http://stackoverflow.com/questions/6452791/interacting-with-canvas-rectangle/6452867#6452867) may help. – pimvdb Feb 28 '12 at 23:42
  • Possible duplicate http://stackoverflow.com/questions/5690943/calculate-the-x-y-position-of-a-canvas-point – Soren Feb 28 '12 at 23:43
  • http://stackoverflow.com/questions/5085689/tracking-mouse-position-in-canvas – Soren Feb 28 '12 at 23:44
  • @Jesse i do when i get the answer i need :P alot of my questions didn't get answers :( – Sir Feb 28 '12 at 23:50

2 Answers2

1

Not tried in on a canvas, but maybe it can help (part is jQuery), base rely on DOM function 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;
};
Codebeat
  • 6,501
  • 6
  • 57
  • 99
0

Are you using any javascript libraries? I would suggest wrappping all your images in a div with the same class then doing something like this:

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. You can then do whatever you need to to that element.

Xenology
  • 2,357
  • 2
  • 21
  • 39