bcmcfc
bcmcfc

Reputation: 26825

How do I get the centre co-ordinates of an image using jQuery?

I am allowing users to rotate images using jQuery rotate. However, when they do this, the image flows outside of the containing div and overlaps the controls.

My thinking is that if I can get the co-ordinates of the centre of the image, I can then calculate the maximum radius about which it is rotating and use this value to resize the containing div using $.animate.

How would I go about this in jQuery?

Upvotes: 3

Views: 2477

Answers (2)

dSquared
dSquared

Reputation: 9835

You can use offset or position to get there location then add width/2 and height/2 to those numbers like this:

var location = $('img.selector').offset();
var center = new Object();
center.x = location.left + ($('img.selector').width() / 2);
center.y = location.top + ($('img.selector').height() / 2);

You may want to use outHeight() and outerWidth() instead of the width() and height() if the images have padding or borders of some sort.

I hope this helps!

Upvotes: 1

mck89
mck89

Reputation: 19271

You can calculate the center by using image dimensions when its loaded:

var img = $("#image"),
    loaded = false;

img.load(function(){
   if (loaded) return;
   loaded = true;
   var cx = this.width / 2,
       cy = this.height / 2;
   //If you want center coordinates relative to the document
   var pos = $(this).offset();
   cx += pos.left;
   cy += pos.top;
});

//Trigger the event if the image is already loaded
if(img[0].complete) {
    img.trigger("load");
}

Upvotes: 2

Related Questions