I have an interesting problem that I’ve yet to find a proper solution to. You can view the fiddle here: http://jsfiddle.net/DgN8C/3/. Basically, I have an image of a certain size. That image needs to be scaled down so that the user chosen center point (indicated by the red dot visually and data-center-* attributes [these are percentages based on the image width / height]) is in the middle of the containing div (x,y of 50,50 in the example). So, in an ideal world, given the following image:
<img src="image-source" data-center-x="59.125" data-center-y="37.4296" />
The ideal positioning within a 100 x 100 div would have a height of 138px with a left margin of -72px. This would ensure that the red dot in the center of the image (again, see the fiddle) is aligned to the center of the containing div.
Any help to get me going in the right direction would be greatly appreciated.
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.
Then I do the same thing for height. It looks like jQuery’s
width()andheight()functions keep everything to scale. May require further testing.Then I change the margins.
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
divobject. Previous solution was only scaling larger if necessary.This was a helpful post: jQuery resize to aspect ratio