jquery截图插件的使用

首先感谢http://www.htmleaf.com/Demo/201504211717.html这款插件。

   使用之初,对于插件的结构很是糊涂,首先文件的核心是cropper.js,其次才是mian.js算是一个功能丰富的demo,其中文件包中也有example里边也是不错的demo,含有图片的上传与裁剪,以及裁剪后的上传(example的demo中这是重点,文件中的crop.php演示环境,导致没有搞懂上传,不知道提交的demo是否正确。这也是下来极重要解决的。)

  ①首先配置的是一系列属性,文件的裁剪配置,

    aspectRatio: NaN,  //是自由裁剪还是按照比例16/9(等比例)
    preview: '.img-preview',  //截图时的预览模式

    autoCropArea:0.5,  //定义时初始化时截图框的百分比,大于0小于1的小数。百分数不行

    zoomable: false,  //设置截图的时候是否图片可以由鼠标滑轮缩放 /2016/1/11

    (这部分也只是了解了项目中需要修改的部分,具体在demo中调试)

  ②其次,最重要的是保存替换当前图片为截图,在项目实际情况中的需求是,对商品的图片裁剪后直接生效,就需要讲裁剪的图片保存起来,并且替换当前的,<img 的src的url。由于crop.php没有环境配置,不知道其中的保存原理。

于是联想到main.js中的getCroppedCanvas按钮,该按钮是获得了裁剪后的图片的。但是这个裁剪是一个canvas,就需要学习canvas的图片的保存方式。通过查看,发现保存的关键在main.js中的result = $image.cropper(data.method, data.option);上。通过

alert(result ),发现result是一个HTMLCanvasElement,最后通过学习,HTMLCanvasElementHTMLCanvasElement.toDataURL()能够返回canvas中的image的src.url。具体学习https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement

这样得到的url其实是该图片的base64编码字符串,可以前台通过js处理,也可以传给后台,提交服务器保存的时候让后台python或者java处理。

以下是本渣渣的部分代码,截图实在弹出的模态框种实现的:模态框id="edit-pic-modal"

  

  1 $(".edit-pic").click(function(){
  2         var edit_modal = $("#edit-pic-modal"),
  3             this_img = $(this).closest(".thumbnail").find("img");
  4         if(this_img.attr("src")!="/static/image/add.png"){
  5             var pic_link = $(this).closest(".thumbnail").find("img").attr("src")
  6             //var  pic = $(this).closest(".thumbnail").find("img")
  7             $("#edit-img-content").html("");
  8             var image_content = $("#edit-img-content");
  9             var div=$("<div/>").attr("class","col-md-12");
 10             var img_html_str="<div class='thumbnail img-container'>"
 11                         +"<img src='" + pic_link + "' class='image img-responsive'>"
 12                         +"</div>";
 13             div.html(img_html_str).appendTo(image_content);
 14             edit_modal.modal("show");
 15             var $image = $('.img-container > img'),
 16                 $dataX = $('#dataX'),
 17                 $dataY = $('#dataY'),
 18                 $dataHeight = $('#dataHeight'),
 19                 $dataWidth = $('#dataWidth'),
 20                 $dataRotate = $('#dataRotate'),
 21                 options = {
 22                   aspectRatio: NaN,
 23                   preview: '.img-preview',
 24                   crop: function (data) {
 25                     $dataX.val(Math.round(data.x));
 26                     $dataY.val(Math.round(data.y));
 27                     $dataHeight.val(Math.round(data.height));
 28                     $dataWidth.val(Math.round(data.width));
 29                     $dataRotate.val(Math.round(data.rotate));
 30                   }
 31                 };
 32             $image.on({
 33               'build.cropper': function (e) {
 34                 console.log(e.type);
 35               },
 36               'built.cropper': function (e) {
 37                 console.log(e.type);
 38               },
 39               'dragstart.cropper': function (e) {
 40                 console.log(e.type, e.dragType);
 41               },
 42               'dragmove.cropper': function (e) {
 43                 console.log(e.type, e.dragType);
 44               },
 45               'dragend.cropper': function (e) {
 46                 console.log(e.type, e.dragType);
 47               },
 48               'zoomin.cropper': function (e) {
 49                 console.log(e.type);
 50               },
 51               'zoomout.cropper': function (e) {
 52                 console.log(e.type);
 53               }
 54             }).cropper(options);
 55 
 56 
 57             // Methods
 58             $(document.body).on('click', '[data-method]', function () {
 59               var data = $(this).data(),
 60                   $target,
 61                   result;
 62 
 63               if (data.method) {
 64                 data = $.extend({}, data); // Clone a new one
 65 
 66                 if (typeof data.target !== 'undefined') {
 67                   $target = $(data.target);
 68                   if (typeof data.option === 'undefined') {
 69                     try {
 70                       data.option = JSON.parse($target.val());
 71                     } catch (e) {
 72                       console.log(e.message+"one");
 73                     }
 74                   }
 75                 }
 76 
 77                 result = $image.cropper(data.method, data.option);//$image的内容没有变化
 78                 var res = result.toDataURL("image/png").split(",");
 79                 if (data.method === 'getCroppedCanvas') {
 80                   //alert("s=="+$('#getCroppedCanvasModal').modal().find('.modal-body').html(result).toDataURL("image/png"));
 81                   $.ajax({
 82                     "type": "POST",
 83                     "url": "/picture/"+shop_id+"/upload/base",
 84                     "dataType": "json",
 85                     "data": {
 86                       "filedata": res[res.length-1]
 87                     },
 88                     "success":function(data){
 89                         if(data.status == 1) {
 90                             edit_modal.modal("hide");
 91                             this_img.attr("src",data.url);
 92                         }else{
 93 
 94                         }
 95                     },
 96                     "error": function(){
 97                         console.log("there is some error happened while editing.");
 98                     }
 99                 })
100                 }
101 
102                 if ($.isPlainObject(result) && $target) {
103                   try {
104                     $target.val(JSON.stringify(result));
105                   } catch (e) {
106                     console.log(e.message + "two");
107                   }
108                 }
109 
110               }
111             }).on('keydown', function (e) {
112 
113               switch (e.which) {
114                 case 37:
115                   e.preventDefault();
116                   $image.cropper('move', -1, 0);
117                   break;
118 
119                 case 38:
120                   e.preventDefault();
121                   $image.cropper('move', 0, -1);
122                   break;
123 
124                 case 39:
125                   e.preventDefault();
126                   $image.cropper('move', 1, 0);
127                   break;
128 
129                 case 40:
130                   e.preventDefault();
131                   $image.cropper('move', 0, 1);
132                   break;
133               }
134             });
135 
136         }else{
137             return 0;
138         }
139     });

当然代码太长,太渣,高手估计50行足以,才外还有的bug就是,点击第一次$(".edit-pic").click(function()还算是ok,当第二次点击的时候会报错:

 ② 2016/1/09修正了第二次点击错误 就是上段代码第78行提示的:

var res = result.toDataURL("image/png").split(",");  toDataURL is not function的问题,主要原因是调试发现$image的对象再次编辑的时候没有变化,刚还是第一次的内容,导致canvas没有刷新(问题描述可能不太准确,但是就是$image的问题).

解决方法:在77,78行将$image重新取值更新一下,或者如下
  var $new_image = $('.img-container > img');
  var result = $new_image.cropper(data.method, data.option);

//一下是在系统实际应用中出现的另外的问题
修正每次编辑完,其他图片也跟正变化的问题,
  原因:系统中的模态框的提交按钮没有提交后没有解绑click事件,导致每次编辑后,同一个模态框绑定了多了一次,原来的url自然就被后边的更新了,也让我认识到了unbind()函数的作用;
  解决方法:每次执行
    $("#edit-pic-modal").find('[data-method="getCroppedCanvas"]').unbind().on('click', function () {
  的时候先进行解绑事件


  

  

原文地址:https://www.cnblogs.com/mxh1099/p/5050402.html