2

我有一个有趣的问题,我还没有找到合适的解决方案。您可以在此处查看小提琴:http: //jsfiddle.net/DgN8C/3/。基本上,我有一个特定大小的图像。该图像需要按比例缩小,以便用户选择的中心点(由视觉上的红点和 data-center-* 属性表示[这些是基于图像宽度/高度的百分比])位于包含 div 的中间( x,y 在示例中为 50,50)。因此,在理想世界中,给定下图:

<img src="image-source" data-center-x="59.125" data-center-y="37.4296" />

在 100 x 100 div 内的理想定位是高度为 138 像素,左边距为 -72 像素。这将确保图像中心的红点(再次参见小提琴)与包含 div 的中心对齐。

任何能让我朝着正确方向前进的帮助将不胜感激。

4

1 回答 1

3

我想我明白了。您可能需要检查图像是否按比例缩放。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 ) );
}

然后我对身高做同样的事情。看起来 jQuerywidth()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)));

编辑好的,第一次尝试没有保留纵横比。现在应该修好了。http://jsfiddle.net/DgN8C/9/逻辑与下面基本相同,只是我智能选择了宽度或高度进行缩放。仅设置一个将保留纵横比。

编辑一个。http://jsfiddle.net/DgN8C/13/这会放大和缩小以适应包含的div对象。以前的解决方案只是在必要时扩大规模。


这是一篇很有帮助的帖子:jQuery resize to aspect ratio

于 2012-10-24T23:10:27.500 回答