Skip to content

Instantly share code, notes, and snippets.

@cornchz
Created September 19, 2011 02:47
Show Gist options
  • Save cornchz/1225888 to your computer and use it in GitHub Desktop.
Save cornchz/1225888 to your computer and use it in GitHub Desktop.
clipImage
/**
* Clip images, given as jQuery objects.
* @param img_obj jQuery Object
*/
window.clipImage = (function() {
return function (img_obj) {
function setViewport(img, x, y, width, height) {
img.style.left = "-" + parseInt(x) + 'px';
img.style.top = "-" + parseInt(y) + 'px';
img.style.width = width === 'auto' ? width : parseInt(width) + 'px';
img.style.height = height === 'auto' ? height : parseInt(height) + 'px';
}
function _clipImage(img, maxwidth, maxheight) {
img.style.display = 'block';
img.style.position = 'absolute';
myImage = new Image();
myImage.src = img.src;
myImage.onload = function () {
var rx = myImage.width / maxwidth,
ry = myImage.height / maxheight;
if(rx > ry){
var dx = parseInt((myImage.width/ry - maxwidth) / 2);
setViewport(img, dx, 0, 'auto', maxheight);
} else {
var dy = parseInt((myImage.height/rx - maxheight) / 2);
setViewport(img, 0, dy, maxwidth, 'auto');
}
};
}
img_obj.each(function (i, img) {
var $img = $(img);
var maxwidth = $img.width();
var maxheight = $img.height();
$img.attr('width', null);
$img.attr('height', null);
var viewport = $('<div style="overflow: hidden; position: relative; width:'+maxwidth+'px; height:'+maxheight+'px;"></div>');
$img.before(viewport);
viewport.append($img);
_clipImage(img, maxwidth, maxheight);
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment