Skip to content

Instantly share code, notes, and snippets.

@GuillaumeJasmin
Last active December 30, 2015 11:09
Show Gist options
  • Save GuillaumeJasmin/7820571 to your computer and use it in GitHub Desktop.
Save GuillaumeJasmin/7820571 to your computer and use it in GitHub Desktop.
Dirctive AngularJS
app.directive('resizeImg', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var src = attrs.ngSrc;
var maxWidth = attrs.width;
var maxHeight = attrs.height;
var newWidth;
var newHeight;
var img = new Image();
img.onload = function() {
if( (maxWidth / this.width ) > (maxHeight / this.height) ) {
newWidth = maxWidth;
newHeight = Math.round( (maxWidth * this.height) / this.width);
}
else {
newHeight = maxHeight;
newWidth = Math.round( (maxHeight * this.width) / this.height);
}
element.css('display', 'none');
element.parent().css({
'background-image': 'url(' + src + ')',
'background-size': newWidth + 'px ' + newHeight + 'px',
'background-position': 'center center',
'display': 'block',
'width': maxWidth + 'px',
'height': maxHeight + 'px'
});
}
img.src = src;
}
}
});
// HTML
//
// <div>
// <img src="image.jpg" resize-img height="300" width="200" />
// <div>
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment