我想我已经明白了。您可能需要检查图像是否需要缩放。 http://jsfiddle.net/DgN8C/7/
基本上,我缩放,然后设置边距。限制因素或告诉我们是否需要缩放图像的因素将是双方中较小的一个。因此,如果点为80%,我们需要点和右侧(image_width * 20%
)之间的像素宽度以适应我们的封闭div对象(obj_width/2
)。注意if语句。
因此,如果我们的图像不适合对象,我们需要将其放大。不知怎的,我做到了。好好想想。
// First, we need to scale image so that it will fit within the dimensions
// of the object. The limiting factor is shorter side of the pixel
limit = Math.min(center_x, 100-center_x)/100.0;
// Check if image needs to be scaled
if ((obj_width/2) > (limit*img.width())) {
// Image must be scaled
chunk = limit * 2; // Section we need from image
// image_width * chunk = obj_width
img.width(Math.ceil(obj_width/chunk));
}
然后我做同样的事情的高度。它看起来像jQuery的width()
和height()
函数保持一切规模。可能需要进一步测试。
然后我改变边距。
img.css('margin-left', -1 * (((center_x/100.0)*img.width()) - (obj_width/2)));
img.css('margin-top', -1 * (((center_y/100.0)*img.height()) - (obj_height/2)));
EDIT好的,在第一次尝试未保留宽高比。现在应该修复。 http://jsfiddle.net/DgN8C/9/除了我智能地选择宽度或高度来缩放外,逻辑与下面的基本相同。只设置一个将保持宽高比。
编辑一个。 http://jsfiddle.net/DgN8C/13/这将缩放比例变大以适合包含div
对象。如果需要,以前的解决方案只能扩大。
这是一个有用的帖子:jQuery resize to aspect ratio
这几乎正是我试图完成:http://jsfiddle.net/W4seR/10/。如果这里的红点是我的图像上的红点,并且图像填充了空间(以红点为中心),那就完美了。 – sdover102