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(' ');
}).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.
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(' ');
}).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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With