Return to Snippet

Revision: 39608
at January 19, 2011 03:00 by adamcoulombe


Initial Code
(function($){
 $.fn.extend({
 	cropToSquare : function(options) {
		var defaults = {
			size: 100
		};	
	  var options = $.extend(defaults, options);	  
	  return this.each(function() {
				var constrainTo = options.size;
				var width = $(this).width();
				var height = $(this).height();
				
				if(height>width){
					var ratio = height/width;
					$(this).width(constrainTo).height(constrainTo*ratio);
					var marg = ($(this).height() - constrainTo) /2;
					$(this).css({marginTop:-marg});
				}else{
					var ratio = width/height;
					$(this).height(constrainTo).width(constrainTo*ratio);
					var marg = ($(this).width() - constrainTo) /2;
					$(this).css({marginLeft:-marg});					
				}
				var imgWrap=$('<div class="imgWrap" />').css({width:constrainTo,height:constrainTo,overflow:'hidden'});	;
				$(this).wrap(imgWrap);
	  });  
	}
 });
})(jQuery);

$(function(){
	$('img').cropToSquare();
});

Initial URL

                                

Initial Description

                                

Initial Title
jQuery Crop and Constrain to square dimensions

Initial Tags
jquery

Initial Language
jQuery