Posted By

adamcoulombe on 01/19/11


Tagged

jquery square dimensions crop


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

virendrakryadav


jQuery Crop and Constrain to square dimensions


 / Published in: jQuery
 

  1. (function($){
  2. $.fn.extend({
  3. cropToSquare : function(options) {
  4. var defaults = {
  5. size: 100
  6. };
  7. var options = $.extend(defaults, options);
  8. return this.each(function() {
  9. var constrainTo = options.size;
  10. var width = $(this).width();
  11. var height = $(this).height();
  12.  
  13. if(height>width){
  14. var ratio = height/width;
  15. $(this).width(constrainTo).height(constrainTo*ratio);
  16. var marg = ($(this).height() - constrainTo) /2;
  17. $(this).css({marginTop:-marg});
  18. }else{
  19. var ratio = width/height;
  20. $(this).height(constrainTo).width(constrainTo*ratio);
  21. var marg = ($(this).width() - constrainTo) /2;
  22. $(this).css({marginLeft:-marg});
  23. }
  24. var imgWrap=$('<div class="imgWrap" />').css({width:constrainTo,height:constrainTo,overflow:'hidden'}); ;
  25. $(this).wrap(imgWrap);
  26. });
  27. }
  28. });
  29. })(jQuery);
  30.  
  31. $(function(){
  32. $('img').cropToSquare();
  33. });

Report this snippet  

You need to login to post a comment.