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_height = obj.height(),
obj_width = obj.width();
var img = obj.find('img'),
center_x = img.attr('data-center-x'),
center_y = img.attr('data-center-y'),
image_height = img.height(),
image_width = img.width(),
limit, 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
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 do that for height
limit = Math.min(center_y, 100-center_y) / 100.0;
if ((obj_height/2) > (limit*img.height())) {
chunk = limit * 2;
img.height( Math.ceil( obj_height / chunk ) );
}
// Now we have the image scaled
// Now, 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)));
});
};
$('.photo-2').expand_photos_to_div();