Skip to content

Instantly share code, notes, and snippets.

@oliger
Created November 20, 2012 09:59
Show Gist options
  • Save oliger/4117064 to your computer and use it in GitHub Desktop.
Save oliger/4117064 to your computer and use it in GitHub Desktop.
Javascript Image Mask
.ui-mask {
position: relative;
overflow: hidden;
}
.ui-mask img {
position: absolute;
top: 0;
left: 0;
}
.ui-mask-high img {
height: 100%;
width: auto;
}
.ui-mask-wide img {
width: 100%;
height: auto;
}
function maskImage($img) {
var $mask = $img.parents(".ui-mask");
var maskWidth = $mask.width();
var maskHeight = $mask.height();
$img.on("load", function() {
var maskRatio = maskWidth / maskHeight;
var imageRatio = this.width / this.height;
if (maskRatio === imageRatio) return;
if (maskRatio > imageRatio) {
$mask.addClass("ui-mask-wide");
$img.css({ top: (maskHeight - this.height) / 2 });
} else {
$mask.addClass("ui-mask-high");
$img.css({ left: (maskWidth - this.width) / 2 });
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment