如何使用jQuery获取图像的中心坐标?

3

我使用jQuery rotate允许用户旋转图像,但是当他们这样做时,图像会流出包含它的 div 并覆盖控件。

我的想法是,如果我可以获取图像中心的坐标,然后计算其最大旋转半径,再使用$.animate调整包含它的 div 的大小。

我该如何在 jQuery 中实现这一点?


2
您想将图像的中心作为相对坐标还是绝对坐标? - Mikhail
1
height / 2width / 2 有什么问题? - Rob
2个回答

2
您可以在图像加载时使用图像尺寸来计算中心点:
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");
}

1

您可以使用offsetposition来获取它们的位置,然后将宽度/2和高度/2添加到这些数字中,如下所示:

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);

如果图像具有某种填充或边框,您可能希望使用outHeight()和outerWidth()而不是width()和height()。

希望这可以帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接