How to zoom in an image and center it? - javascript

Any Idea how to zoom in a image on particular point using javascript, css ? I am using webkit based browser.
I can zoom by specifying zoom property , like `elem.style.zoom="150%",
Main problem is I cannot center the image where I want to zoom.
I can get the point where I want to zoom using mouseclick.

As I said in my comment above, I would avoid the zoom css property and stick to just javascript. I managed to throw together the following code which works pretty well for the first click, really all it needs is a little more dynamically (even a word?).
<html>
<head>
<script type="text/javascript">
function resizeImg (img)
{
var resize = 150; // resize amount in percentage
var origH = 200; // original image height
var origW = 200; // original image width
var mouseX = event.x;
var mouseY = event.y;
var newH = origH * (resize / 100) + "px";
var newW = origW * (resize / 100) + "px";
// Set the new width and height
img.style.height = newH;
img.style.width = newW;
var c = img.parentNode;
// Work out the new center
c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
c.scrollTop = (mouseY * (resize / 100)) - (newH / 2) / 2;
}
</script>
<style type="text/css">
#Container {
position:relative;
width:200px;
height:200px;
overflow:hidden;
}
</style>
</head>
<body>
<div id="Container">
<img alt="Click to zoom" onclick="resizeImg(this)"
src="https://picsum.photos/200" />
</div>
</body>
</html>
It works in Google Chrome and IE, not sure about others. Like I said hopefully it will point you in the right direction.

What has to be done.
Get the location of the click inside the image. This might seem easy but it is not because the pageX and pageY of the event hold the coordinates in regard to the document. To calculate where inside the image someone clicked you need to know the position of the image in the document. But to do this you need to factor in all the parents of it, as well as if they are relative/absolute/static positioned .. it gets messy..
calculate the new center (the click position scaled - the top/left position of the container)
scale the image and scroll the container to the new center
if you do not mind using jQuery for it then use the following (tested)
<script type="text/javascript">
$(document).ready(
function(){
$('#Container img').click(
function( event ){
var scale = 150/100;
var pos = $(this).offset();
var clickX = event.pageX - pos.left;
var clickY = event.pageY - pos.top;
var container = $(this).parent().get(0);
$(this).css({
width: this.width*scale,
height: this.height*scale
});
container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);
}
);
</script>
and the html needed
<div id="Container">
<img alt="Click to zoom" src="http://sstatic.net/so/img/logo.png" />
</div>

In following code, the image is amplified at the mouse click point - the image is amplified, but the point where you clicked remains under your mouse cursor, and the size of the frame remains the same. Right-click to go back to original display ratio.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
div {
width: 400px;
height: 600px;
overflow: hidden;
}
img {
position: relative
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
var imageOffset_x = 0;
var imageOffset_y = 0;
function onZoom()
{
var mouseInFrame_x = event.x;
var mouseinFrame_y = event.y;
var mouseInImage_x = imageOffset_x + mouseInFrame_x;
var mouseInImage_y = imageOffset_y + mouseinFrame_y;
imageOffset_x += mouseInImage_x * 0.16;
imageOffset_y += mouseInImage_y * 0.16;
var image = $('#container img');
var imageWidth = image.width();
var imageHeight = image.height();
image.css({
height: imageHeight * 1.2,
width: imageWidth * 1.2,
left: -imageOffset_x,
top: -imageOffset_y
});
}
function onRightClick() {
imageOffset_x = 0;
imageOffset_y = 0;
$('#container img').css({
height: 600,
width: 400,
left: 0,
top: 0
});
return false;
}
</script>
</head>
<body>
<a id="zoom" href="#" onclick="onZoom();">Zoom</a>
<div id="container">
<img src="~/Images/Sampple.jpg" width="400" height="600" onclick="onZoom();" oncontextmenu="onRightClick(); return false;"/>
</div>
</body>
</html>

Related

How to scroll an image over fixed content?

I'm building a Shopify site, and want an overlay image to cover the top content when you land on the website. Then when you scroll, this overlay image moves up and off the screen revealing the website.
I found some javascript that does this, but the main website scrolls with the overlay image. Is there a way to have it scroll on its own and not scroll the content behind?
Here's what I have so far:
var container = document.getElementById('overlay-container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('overlay-background-image')[0];
// var square2 = document.getElementsByClassName('overlay-logo')[1];
// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
var scrollTop = window.pageYOffset || window.scrollTop;
var scrollPercent = scrollTop / scrollArea || 0;
square1.style.bottom = -100 * (1 - scrollPercent * 1.5) + 'vh';
// square2.style.top = 800 - scrollPercent*window.innerHeight*0.6 + 'px';
});
// Global variable to control the scrolling behavior
const step = 30; // For each 30px, change an image
function trackScrollPosition() {
const y = window.scrollY;
const label = Math.min(Math.floor(y / 30) + 1, 20);
const imageToUse = fruitImages[label];
// Change the background image
$('.image-container').css('background-image', `url('${imageToUse}')`);
}
$(document).ready(() => {
$(window).scroll(() => {
trackScrollPosition();
})
})
.overlay-container {
position: relative;
max-width: 100%;
}
.overlay-background-image {
position: absolute;
z-index: 5;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="overlay-container">
<div class="overlay-background-image">
<img style="height: 100vh;" src="https://cdn.shopify.com/s/files/1/0608/2225/7886/files/01_-_Landing_Page.png?v=1636020266" />
</div>
</div>
Edit:
I misread the question.
Original answer:
This will automatically scroll the image offscreen once the page is loaded. (Not what the question wanted)
I'd recommend using css rather than JavaScript for this.
body {
margin: 0px;
}
.overlay-background-image {
animation-fill-mode: forwards;
animation-name: shop_reveal;
animation-duration: 3s;
position: absolute;
width: 100vw;
background-size: calc(100vh * 1440/767);
height: 100vh;
background-image: url('https://cdn.shopify.com/s/files/1/0608/2225/7886/files/01_-_Landing_Page.png?v=1636020266');
}
#keyframes shop_reveal {
from {
bottom: 0px
}
to {
bottom: 100vh
}
}
<div class="overlay-container">
<div class="overlay-background-image">
</div>
</div>
Edited answer:
This will scroll the image along with the scrollbar.
<div class="overlay-container">
<div class="overlay-background-image">
</div>
</div>```
<!-- end snippet -->
pagebox is the content that will be revealed when the user scrolls the page.
<!-- language: lang-css -->
```#pagebox {
position: absolute;
}```
<!-- end snippet -->
Give pagebox absolute positioning so that it's position can be set in JavaScript and it doesn't push the image.
<!-- language: lang-javascript -->
```var container = document.getElementById('overlay-container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('overlay-background-image')[0];
// var square2 = document.getElementsByClassName('overlay-logo')[1];
var p = document.getElementById("pagebox");
// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
var scrollTop = window.pageYOffset || window.scrollTop;
var scrollPercent = scrollTop / scrollArea || 0;
square1.style.bottom = p.style.marginTop = -100 * (1 - scrollPercent * 1.5) + 'vh';
// square2.style.top = 800 - scrollPercent*window.innerHeight*0.6 + 'px';
});```
<!-- end snippet -->
As the page is scrolled. The image overlay is moved up by this code. However the normal functioning of the scrolling is still in effect so the rest of the page moves up with it. In order to counteract this. The position of the content underneath the image is moved down by the amount the page is scrolled.
(simply using position:sticky would prevent the content underneath the page from exceeding the height of the window so can't be used)

How can I move elements into view when the window is resized?

I have a project which I need to do an aquarium and the fishes inside gather on click.
I have done everything, but here is the problem, the program should work on resize.
What I am trying to say. If I resize the browser window, the fishes should re-appear in the visible spot of the window and continue swimming.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color:aqua; width:100%; height:100%;padding:0; margin:0;}
img{width:50px; height:50px;}
div{position:absolute;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
i = 0;
function swim(fishid){
newLeft = Math.random()*1200; // due to new width
newTop = Math.random()*600; //due to new height
do_move(fishid, newTop, newLeft, Math.random()*1000);
}
function do_move(fishid, topPos, leftPos, timeToMove=0){
$("#"+fishid).css({"transform": "rotateY(0deg)"});
ll = leftPos + 'px';
tt = topPos + 'px';
if( parseInt($("#"+fishid).css('left'))>leftPos){
$("#"+fishid).css({"transform": "rotateY(180deg)"});
}
$("#"+fishid).animate({"left": ll, "top": tt}, 1000+timeToMove, function(){swim(fishid);});
}
$(document).ready(function(){
let fishes = Math.random()*5+5;
for(i=0; i<fishes; i++){
$("body").append('<div id="fish'+ i + '"><img src="http://icons.iconarchive.com/icons/icons8/ios7/256/Animals-Fish-icon.png"></div>');
swim("fish" + i);
}
$("*").click(function(ev){
$("div").each(function(){
$(this).stop();
do_move($(this).attr("id"), ev.pageY-25, ev.pageX);
});
});
$ ( window ).resize(function(){});// I have to do it with this also
});
</script>
</head>
<body>
</body>
</html>
The resize event will be triggered whenever you resize your screen. You can easily get the screens inner width and height similarly.
$(window).resize(function(e){
console.log($(this).innerWidth())
console.log($(this).innerHeight())
});
Use the actual window dimensions instead of hard-coded values:
newLeft = Math.random() * window.innerWidth * 0.9;
newTop = Math.random() * window.innerHeight * 0.9;
No resize event handler is needed since the swim() function is called repeatedly. This means that there's a brief period where fish can escape the window, but it's resolved after one program cycle. Putting overflow: hidden on the body eliminates scrollbars during resize.
I've introduced an arbitrary reducer of 90% to allow for fish size. That could be adjusted.
Fiddle demo
newLeft = Math.random() *$( window ).width();
newTop = Math.random() *$( window ).height()
https://jsfiddle.net/rkv88/nh1buw8o/

Image move with mouse position - box issue?

I had originally taken some information from here and expanded on it: onextrapixel.com/examples/interactive-background/index4.html
I have instead incorporated the image to move with mouse position on the page, however there seems to be an issue with there being a top "box" that cuts off some of the hovered image. You can see it in action on a sample page here
My css:
.top-image {
background:url('http://i.imgur.com/wZRaMrB.png');
position:absolute ;
top:400px;
width:100%;
z-index:0;
height:100%;
background-repeat: no-repeat;
}
My js:
$(document).ready(function() {
var movementStrength = 25;
var height = movementStrength / $(window).height();
var width = movementStrength / $(window).width();
$("body").mousemove(function(e){
var pageX = e.pageX - ($(window).width() / 2);
var pageY = e.pageY - ($(window).height() / 2);
var newvalueX = width * pageX * -1 - 25;
var newvalueY = height * pageY * -1 - 50;
$('.top-image').css("background-position", newvalueX+"px "+newvalueY+"px");
});
});
I also hope to repeat this for the right side of the page.
After some suggesting in the comments here is the jsfiddle https://jsfiddle.net/yx1w8ysr/#&togetherjs=D4Q1xTfcaO
If you know the image's size beforehand, you can set the size of your div fixedly and don't need to use background-size:contain. Instead set it to some relative value (less than 100%) so that you have a padding around for the movement of the background image. However if you don't know the size of the image, you should use background-size:contain to ensure that your image sits right inside your div container. However with this approach we cannot control the size of the image anymore. That means you cannot use background-position to move the image around (because the size fits its parent, moving will cause the image be cut off).
So you need some another wrapper/container and move your inner div (.top-image) instead of changing the background-position.
Here is the detailed code:
var movementStrength = 25;
var w = $(window).width();
var h = $(window).height();
$(window).mousemove(function(e) {
var pageX = (e.pageX - w / 2) / w / 2;
var pageY = (e.pageY - h / 2) / h / 2;
var newvalueX = pageX * movementStrength;
var newvalueY = pageY * movementStrength;
$('.top-image').css({
left: newvalueX + 'px',
top: newvalueY + 'px'
});
});
.container {
padding: 25px;
width: 35%;
height: 35%;
position: absolute;
top: 400px;
}
.top-image {
background: url('http://i.imgur.com/wZRaMrB.png');
position: absolute;
background-size: contain;
width: 100%;
z-index: 0;
height: 100%;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class="top-image"></div>
</div>

Resize div with drag handle when rotated

I could find similar questions involving jQuery UI lib, or only css with no handle to drag, but nothing with pure maths.
What I try to perform is to have a resizable and rotatable div. So far so easy and I could do it.
But it gets more complicate when rotated, the resize handle does calculation in opposite way: it decreases the size instead of increasing when dragging away from shape.
Apart from the calculation, I would like to be able to change the cursor of the resize handle according to the rotation to always make sense.
For that I was thinking to detect which quadrant is the resize handle in and apply a class to change cursor via css.
I don't want to reinvent the wheel, but I want to have a lightweight code and simple UI. So my requirement is jQuery but nothing else. no jQuery UI.
I could develop until achieving this but it's getting too mathematical for me now.. I am quite stuck that's why I need your help to detect when the rotation is enough to have the calculation reversed.
Eventually I am looking for UX improvement if anyone has an idea or better examples to show me!
Here is my code and a Codepen to try: http://codepen.io/anon/pen/rrAWJA
<html>
<head>
<style>
html, body {height: 100%;}
#square {
width: 100px;
height: 100px;
margin: 20% auto;
background: orange;
position: relative;
}
.handle * {
position: absolute;
width: 20px;
height: 20px;
background: turquoise;
border-radius: 20px;
}
.resize {
bottom: -10px;
right: -10px;
cursor: nwse-resize;
}
.rotate {
top: -10px;
right: -10px;
cursor: alias;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function()
{
new resizeRotate('#square');
});
var resizeRotate = function(targetElement)
{
var self = this;
self.target = $(targetElement);
self.handles = $('<div class="handle"><div class="resize" data-position="bottom-right"></div><div class="rotate"></div></div>');
self.currentRotation = 0;
self.positions = ['bottom-right', 'bottom-left', 'top-left', 'top-right'];
self.bindEvents = function()
{
self.handles
//=============================== Resize ==============================//
.on('mousedown', '.resize', function(e)
{
// Attach mouse move event only when first clicked.
$(document).on('mousemove', function(e)
{
var topLeft = self.target.offset(),
bottomRight = {x: topLeft.left + self.target.width(), y: topLeft.top + self.target.height()},
delta = {x: e.pageX - bottomRight.x, y: e.pageY - bottomRight.y};
self.target.css({width: '+=' + delta.x, height: '+=' + delta.y});
})
.one('mouseup', function(e)
{
// When releasing handle, round up width and height values :)
self.target.css({width: parseInt(self.target.width()), height: parseInt(self.target.height())});
$(document).off('mousemove');
});
})
//============================== Rotate ===============================//
.on('mousedown', '.rotate', function(e)
{
// Attach mouse move event only when first clicked.
$(document).on('mousemove', function(e)
{
var topLeft = self.target.offset(),
center = {x: topLeft.left + self.target.width() / 2, y: topLeft.top + self.target.height() / 2},
rad = Math.atan2(e.pageX - center.x, e.pageY - center.y),
deg = (rad * (180 / Math.PI) * -1) + 135;
self.currentRotation = deg;
// console.log(rad, deg);
self.target.css({transform: 'rotate(' + (deg)+ 'deg)'});
})
.one('mouseup', function(e)
{
$(document).off('mousemove');
// console.log(self.positions[parseInt(self.currentRotation/90-45)]);
$('.handle.resize').attr('data-position', self.positions[parseInt(self.currentRotation/90-45)]);
});
});
};
self.init = function()
{
self.bindEvents();
self.target.append(self.handles.clone(true));
}();
}
</script>
</head>
<body>
<div id="all">
<div id="square"></div>
</div>
</body>
</html>
Thanks for the help!
Here is a modification of your code that achieves what you want:
$(document).ready(function() {
new resizeRotate('#square');
});
var resizeRotate = function(targetElement) {
var self = this;
self.target = $(targetElement);
self.handles = $('<div class="handle"><div class="resize" data-position="bottom-right"></div><div class="rotate"></div></div>');
self.currentRotation = 0;
self.w = parseInt(self.target.width());
self.h = parseInt(self.target.height());
self.positions = ['bottom-right', 'bottom-left', 'top-left', 'top-right'];
self.bindEvents = function() {
self.handles
//=============================== Resize ==============================//
.on('mousedown', '.resize', function(e) {
// Attach mouse move event only when first clicked.
$(document).on('mousemove', function(e) {
var topLeft = self.target.offset();
var centerX = topLeft.left + self.target.width() / 2;
var centerY = topLeft.top + self.target.height() / 2;
var mouseRelativeX = e.pageX - centerX;
var mouseRelativeY = e.pageY - centerY;
//reverse rotation
var rad = self.currentRotation * Math.PI / 180;
var s = Math.sin(rad);
var c = Math.cos(rad);
var mouseLocalX = c * mouseRelativeX + s * mouseRelativeY;
var mouseLocalY = -s * mouseRelativeX + c * mouseRelativeY;
self.w = 2 * mouseLocalX;
self.h = 2 * mouseLocalY;
self.target.css({
width: self.w,
height: self.h
});
})
.one('mouseup', function(e) {
$(document).off('mousemove');
});
})
//============================== Rotate ===============================//
.on('mousedown', '.rotate', function(e) {
// Attach mouse move event only when first clicked.
$(document).on('mousemove', function(e) {
var topLeft = self.target.offset(),
center = {
x: topLeft.left + self.target.width() / 2,
y: topLeft.top + self.target.height() / 2
},
rad = Math.atan2(e.pageX - center.x, center.y - e.pageY) - Math.atan(self.w / self.h),
deg = rad * 180 / Math.PI;
self.currentRotation = deg;
self.target.css({
transform: 'rotate(' + (deg) + 'deg)'
});
})
.one('mouseup', function(e) {
$(document).off('mousemove');
$('.handle.resize').attr('data-position', self.positions[parseInt(self.currentRotation / 90 - 45)]);
});
});
};
self.init = function() {
self.bindEvents();
self.target.append(self.handles.clone(true));
}();
}
The major changes are the following:
In the resize event, the mouse position is transformed to the local coordinate system based on the current rotation. The size is then determined by the position of the mouse in the local system.
The rotate event accounts for the aspect ratio of the box (the - Math.atan(self.w / self.h) part).
If you want to change the cursor based on the current rotation, check the angle of the handle (i.e. self.currentRotation + Math.atan(self.w / self.h) * 180 / Math.PI). E.g. if you have a cursor per quadrant, just check if this value is between 0..90, 90..180 and so on. You may want to check the documentation if and when negative numbers are returned by atan2.
Note: the occasional flickering is caused by the box not being vertically centered.
Nico's answer is mostly correct, but the final result calculation is incorrect -> which is causing the flickering BTW. What is happening is the increase or decrease in size is being doubled by the 2x multiplication. The original half-width should be added to the new half-width to calculate the correct new width and height.
Instead of this:
self.w = 2 * mouseLocalX;
self.h = 2 * mouseLocalY;
It should be this:
self.w = (self.target.width() / 2) + mouseLocalX;
self.h = (self.target.height() / 2) + mouseLocalY;

Javascript mouse click coordinates for image

The assignment says "Your task is to write an HTML file that contains JavaScript that will randomly display one of the images above. If the page is refreshed in the browser, you should get another random image." so I did it.
Now it says "When the user clicks anywhere on the image, display an alert window that shows the X and Y position of where the click occurred relative to the image". Here is my code:
<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">
var imageURLs = [
"p1.jpg"
, "p2.jpg"
, "p3.jpg"
, "p4.jpg"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"Some alt text\"/>';
return img;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(getImageTag());
</script>
</body>
</html>
You can actually use HTML for this. The image tag has an attribute known as ismap.
What this attribute does is specify that an image is part of a server-side image map. When clicking on such map, the click coordinates are sent to the server as a url query string.
Images must be nested under links for this to work. Here is an example
<a href="http://www.google.com">
<img src="myimage.png" alt="My Image" ismap">
</a>
If you can't use image maps for this, here is a javascript/jquery solution
First, you need to include the jQuery library at the bottom of your body tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
$(document).ready(function() {
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert("X Coordinate: " + x + " Y Coordinate: " + y);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://vignette1.wikia.nocookie.net/seraphina/images/b/b2/Dragonseraphina.jpg/revision/latest?cb=20160103194957" height="200" width="200" alt="dragon">
You listen for the click event, and pass in event as the parameter.
The event.pageX property returns the position of the mouse pointer, relative to the left edge of the document.
The map solution will only give you the client side pixel coordinates. If you'd like to get the pixel coordinate relative to the original image you need the naturalHeight and naturalWidth information which has height and width of the original image.
code:
// https://stackoverflow.com/questions/34867066/javascript-mouse-click-coordinates-for-image
document.getElementById(imageid).addEventListener('click', function (event) {
// https://stackoverflow.com/a/288731/1497139
bounds=this.getBoundingClientRect();
var left=bounds.left;
var top=bounds.top;
var x = event.pageX - left;
var y = event.pageY - top;
var cw=this.clientWidth
var ch=this.clientHeight
var iw=this.naturalWidth
var ih=this.naturalHeight
var px=x/cw*iw
var py=y/ch*ih
alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
});
$(document).ready(function() {
$("img").on("click", function(event) {
bounds=this.getBoundingClientRect();
var left=bounds.left;
var top=bounds.top;
var x = event.pageX - left;
var y = event.pageY - top;
var cw=this.clientWidth
var ch=this.clientHeight
var iw=this.naturalWidth
var ih=this.naturalHeight
var px=x/cw*iw
var py=y/ch*ih
alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://upload.wikimedia.org/wikipedia/commons/7/77/Avatar_cat.png" height="256" width="256" alt="kitten">
example
click on IMG at pixel (445.5,334.125) mouse pos (148.5,49) relative to boundingClientRect at (483.5,64) client image size: 640 x 480 natural image size: 1920 x 1080
$(document).ready(function () {
$("img").on("click", function (event) {
$('#img_coordinate').html("X Coordinate: " + (event.pageX - this.offsetLeft) + "<br/> Y Coordinate: " + (event.pageY - this.offsetTop));
});
});
html
<img src="img/sample.gif" />
<p id="img_coordinate"></p>
little fork ;)
$(document).ready(function() {
$('img').click(function(e) {
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
w = $(this).prop("width"); // Width (Rendered)
h = $(this).prop("height"); // Height (Rendered)
nw = $(this).prop("naturalWidth") ; // Width (Natural)
nh = $(this).prop("naturalHeight") ; // Height (Natural)
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
x = Math.round((left*nw)/w);
y = Math.round((top*nh)/h);
// $('#img_coordinate').html("Left: " + left + " Top: " + top + "nw: "+nw+" nh: "+nh +"x: "+x+" y: "+y);
$('#img_coordinate').html("click x: "+x+" y: "+y);
});
});

Categories