头像裁剪工具jcrop

张映 发表于 2012-08-20

分类目录: nodejs/vue/js/jquery

标签:,

头像裁剪工具目前比较流行的是flash和jquery的。个人觉得用jquery的比较好,因为代码仔细研究一下,基本上能明白怎么回事,想改的话也比较容易。

有一个例子,请参考:jcrop例子demo,是根jcrop的例子改的,添加以下二个特点:

1,居中显示,并且可拖拉,改变截取的大小

2,预览的图片,根拖拉的大小成比例。

以下是js代码,作了简单的封装

  1. <script type="text/javascript">  
  2.   
  3. new cutImage().init();  
  4.   
  5. function cutImage(){  
  6.   
  7.    var oop = this;  
  8.   
  9.    this.option = {  
  10.             x:170,  
  11.             y:110,  
  12.             w:350,  
  13.             h:200,  
  14.             t:'target',  
  15.             p:'preview',  
  16.             o:'aa'  
  17.     }  
  18.   
  19.    this.init = function(){  
  20.         oop.target();  
  21.    }  
  22.   
  23.    this.target = function(){  
  24.       $('#'+oop.option['t']).Jcrop({  
  25.           onChange: oop.updatePreview,  
  26.           onSelect: oop.updatePreview,  
  27.           aspectRatio: 1,  
  28.           setSelect: [ oop.option['x'], oop.option['y'], oop.option['w'],oop.option['h'] ],  
  29.           bgFade:     true,  
  30.           bgOpacity: .5  
  31.        });  
  32.    }  
  33.   
  34.    this.updatePreview = function(obj){  
  35.        if (parseInt(obj.w) > 0)  
  36.        {  
  37.          var rx = $('#'+oop.option['o']).width()/ obj.w;  
  38.          var ry = $('#'+oop.option['o']).height()/ obj.h;  
  39.   
  40.          $('#'+oop.option['p']).css({  
  41.            width: Math.round(rx*$('#'+oop.option['t']).width()) + 'px',  
  42.            height: Math.round(ry*$('#'+oop.option['t']).height()) + 'px',  
  43.            marginLeft: '-' + Math.round(rx * obj.x) + 'px',  
  44.            marginTop: '-' + Math.round(ry * obj.y) + 'px'  
  45.          });  
  46.        }  
  47.        }  
  48. }  
  49. </script>  

jquery jcrop结合jquery ajax upload的话,可以使头像上传截取功能,很人性化。



转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/jsjquery/1456.html

1 条评论

  1. DD 留言

    这个只有预览,没有截取功能,截取功能怎么做呢?如果为传入1880*1440的大型图片,截取一部分,怎么保证显示在180*180的框内保证图片不会萎缩?