JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Image 1</h1>
<h2>Original Image</h2>
<img src="http://f.cl.ly/items/2s0O3A041D0L2p1y2U19/1351085803_wide-off-center_t.jpeg" data-center-x="23.125" data-center-y="31" />
<h2>Cropped / Scaled Image</h2>
<div class="photo-2">
<img src="http://f.cl.ly/items/2s0O3A041D0L2p1y2U19/1351085803_wide-off-center_t.jpeg" data-center-x="23.125" data-center-y="31" />
</div>
<hr/>
<h1>Image 2</h1>
<h2>Original Image</h2>
<img src="http://f.cl.ly/items/2S3n3d3E161n0S0R3b3R/1351086953_test-2_t.jpeg" data-center-x="85.2" data-center-y="87.6" />
<h2>Cropped / Scaled Image</h2>
<div class="photo-2">
<img src="http://f.cl.ly/items/2S3n3d3E161n0S0R3b3R/1351086953_test-2_t.jpeg" data-center-x="85.2" data-center-y="87.6" />
</div>
<hr/>
<h1>Image 3</h1>
<h2>Original Image</h2>
<img src="http://f.cl.ly/items/2l2j3c0B09441o1e0Z1n/Image%202012.10.24%2010:02:47%20AM.png" data-center-x="59.125" data-center-y="37.4296" />
<h2>Cropped / Scaled Image</h2>
<div class="photo-2">
<img src="http://f.cl.ly/items/2l2j3c0B09441o1e0Z1n/Image%202012.10.24%2010:02:47%20AM.png" data-center-x="59.125" data-center-y="37.4296" />
</div>
CSS
.photo, .photo-2 {
width: 100px;
height: 100px;
overflow: hidden;
border: 1px solid red;
}
.photo-2 {
margin-top: 15px;
}
.photo-2 img {
/*height: 158px;*/
/* margin-left: -8px; */
}
JavaScript
$.fn.expand_photos_to_div = function(options) {
var settings = $.extend({
'variable':false
}, options);
return this.each(function() {
var obj = $(this),
obj_width = obj.width(),
obj_height = obj.height();
var img = obj.find('img'),
center_x = img.attr('data-center-x'),
center_y = img.attr('data-center-y'),
chunk;
// 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
var limit_w_percent = Math.min(center_x, 100-center_x) / 100.0,
limit_w_pixels = limit_w_percent * img.width(),
limit_h_percent = Math.min(center_y, 100-center_y) / 100.0,
limit_h_pixels = limit_h_percent * img.height();
// Scale Width or Height?
// Scaling only one will preserve aspect ratio
if (limit_w_pixels/(obj_width/2) < limit_h_pixels/(obj_height/2)) {
// Check if image needs to be scaled
if ((obj_width/2) > limit_w_pixels) {
// Percent of image width that will be shown
chunk = limit_w_percent * 2;
// So the pixel width of our chunk must be
// the width of our object.
// image_width * chunk = obj_width
img.width( Math.ceil( obj_width / chunk ) );
}
} else {
if ((obj_height/2) > limit_h_pixels) {
chunk = limit_h_percent * 2;
img.height( Math.ceil( obj_height / chunk ) );
}
}
// Now that the image is scaled, we can shift 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))
);
...