redviper2100
redviper2100

Reputation: 265

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.

Upvotes: 5

Views: 2961

Answers (2)

rrk
rrk

Reputation: 15846

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>

Upvotes: 3

Dariusz Sikorski
Dariusz Sikorski

Reputation: 4407

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.

Upvotes: 1

Related Questions