我想我已經明白了。您可能需要檢查圖像是否需要縮放。 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