Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the part of an image where the user clicked

Is it possible to find where the user clicked on the image?

I have an image - and onto the image the user can click. And I am trying to find a way, how to get the place, when the user clicked.

like image 909
user1946705 Avatar asked Jan 19 '23 03:01

user1946705


2 Answers

On image click you can find the coordinates where the user clicked using the event object.

$("imageSelector").click(function(e){
  var pos = $(this).position();
  //The following are the x/y coordinates of the mouse click relative to image.
  var x = e.pageX - pos.left;
  var y = e.pageY - pos.top;
});
like image 169
ShankarSangoli Avatar answered Jan 29 '23 00:01

ShankarSangoli


Don't be fooled by methods that fail to take margin, padding, and border into account!

This is the code you need. :

$("#myImage").click ( function (evt) {

    var jThis               = $(this);
    var offsetFromParent    = jThis.position ();
    var topThickness        = (jThis.outerHeight(true) - jThis.height() ) / 2;
    var leftThickness       = (jThis.outerWidth (true) - jThis.width () ) / 2;

    //--- (x,y) coordinates of the mouse click relative to the image.
    var x                   = evt.pageX - offsetFromParent.left - leftThickness;
    var y                   = evt.pageY - offsetFromParent.top  - topThickness;
} );


See it in action at jsFiddle.


like image 36
Brock Adams Avatar answered Jan 29 '23 00:01

Brock Adams