Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get coordinates of clicked on image with Jquery

I have a resized image (with width="100") and a jquery script to output the current coordinates when I click that image.

<img id="image" src="http://localhost/image.jpg" width="100"  >

<script>
   $('#image').mousemove( function(event) {
     window.current_x = Math.round(event.pageX - $('#image').offset().left) ;
     window.current_y = Math.round(event.pageY - $('#image').offset().top);
     window.current_coords = window.current_x + ', ' + window.current_y;
     $('#edit_instants_now').html('Current position: ' + window.current_coords + '.');
   }).mouseleave( function() {
     $('#edit_instants_now').html('&nbsp;');
   }).click( function() {
     $('#edit_instants_click').html('Last click: ' + window.current_coords + '. ');
     document.edit_instant.edit_instant_x.value = window.current_x;
     document.edit_instant.edit_instant_y.value = window.current_y;
   });
</script>

The problem is that I want to get the actual coordinates of the original image and not the resized one.

Do you have any suggestions? Thanks.

like image 675
redviper2100 Avatar asked Sep 27 '22 20:09

redviper2100


2 Answers

var naturalWidth = 100;
$('#image').mousemove(function(event) {
  var img = $('#image');
  console.log(naturalWidth);
  ratio = naturalWidth / img.width();
  window.current_x = (event.pageX - img.offset().left) * ratio;
  window.current_y = (event.pageY - img.offset().top) * ratio;
  window.current_coords = window.current_x + ', ' + window.current_y;
  $('#edit_instants_now').html('Current position: ' + window.current_coords + '.');
}).mouseleave(function() {
  $('#edit_instants_now').html('&nbsp;');
}).click(function() {
  $('#edit_instants_click').html('Last click: ' + window.current_coords + '. ');
  document.edit_instant.edit_instant_x.value = window.current_x;
  document.edit_instant.edit_instant_y.value = window.current_y;
});

$('img').on('load', function(e) {
  naturalWidth = e.target.naturalWidth;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<img id="image" src="http://dummyimage.com/600x400/000/fff" width="100">

<form name="edit_instant">
  <div id="edit_instants_now"></div>
  <div id="edit_instants_click"></div>
  <input name="edit_instant_x">
  <input name="edit_instant_y">
</form>
like image 89
rrk Avatar answered Oct 31 '22 13:10

rrk


Get the size of original image, divide it by size of resized image - this will give you a scale factor, then multiply resulting x,y coordinates of clicked resized image by the scale factor.

Hope this helps.

like image 36
Dariusz Sikorski Avatar answered Oct 31 '22 11:10

Dariusz Sikorski