I think I've got it. You may want to check that the images are to scale. http://jsfiddle.net/DgN8C/7/
Basically, I scale, then set the margins. The limiting factor, or the factor that tells us whether or not we need to scale the image, will be the smaller of the two sides. So if the dot is at 80%, we need the pixel width between the dot and the right side (image_width * 20%
) to be able to fit in our enclosing div object (obj_width / 2
). Note the if statement.
So if our image does not fit in the object, we need to scale it bigger. And somehow I did that. It hurts to think about.
// 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 ) );
}
Then I do the same thing for height. It looks like jQuery's width()
and height()
functions keep everything to scale. May require further testing.
Then I change the margins.
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 Ok, the first attempt was not preserving aspect ratio. Should be fixed now. http://jsfiddle.net/DgN8C/9/ Logic is basically the same as below, except that I intelligently chose either width or height to scale. Setting only one will preserve aspect ratio.
EDIT One more. http://jsfiddle.net/DgN8C/13/ This scales both larger and smaller to fit the containing div
object. Previous solution was only scaling larger if necessary.
This was a helpful post: jQuery resize to aspect ratio