自己仿照github上的例子寫的demo,github上的例子太抽象了,自己寫的最適合自己,通俗易懂。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link href="./css/cropper.css" rel="stylesheet"> <style> img { max-width: 100%; /* This rule is very important, please do not ignore this! */ } .prev{ display: inline-block; } </style> </head> <body> <div class="container"> <img id="image" src="./img/picture.jpg"> </div> <br><br> <!--crop是對剪切窗口的操作,move是對圖片的操作--> <div> <input type="button" value="crop" id="btnCrop" /> <input type="button" value="move" id="btnMove" /> <input type="button" value="16:9" id="169"> <input type="button" value="1:1" id="11"> <input type="button" value="get" id="getCanvas"> </div> <br><br> <!--圖片截取的結果顯示在這里--> <div class="prev" style="width: 500px; height: 500px; overflow: hidden"></div> <div class="prev" style="width: 300px; height: 300px; overflow: hidden"></div> <div class="prev" style="width: 200px; height: 200px; overflow: hidden"></div> <br><br> <div id="getCroppedCanvas" style="width:500px; height:500px; overflow:hidden;"></div> <script src="./js/jquery-1.11.3.min.js"></script> <script src="./js/cropper.js"></script> <script> $(function(){ var image = document.getElementById("image"); //可以通過$().cropper(options)方法來設置參數。如果想改變全局默認參數,可以使用$.fn.cropper.setDefaults(options)方法。 var cropper = new Cropper(image, { aspectRatio: 16 / 9, //寬高比 preview: '.prev', //預覽窗口 guides: false, //裁剪框的虛線 autoCropArea: 0.5, //0-1之間的數值,定義自動剪裁區域的大小,默認0.8 dragCrop: true, //是否允許移除當前的剪裁框,並通過拖動來新建一個剪裁框區域 movable: true, //是否允許移動剪裁框 resizable: true, //是否允許改變裁剪框的大小 zoomable: true, //是否允許縮放圖片大小 mouseWheelZoom: true, //是否允許通過鼠標滾輪來縮放圖片 touchDragZoom: true, //是否允許通過觸摸移動來縮放圖片 rotatable: true, //是否允許旋轉圖片 minContainerWidth: 200, //容器的最小寬度 minContainerHeight: 200, //容器的最小高度 minCanvasWidth: 0, //canvas 的最小寬度(image wrapper) minCanvasHeight: 0, //canvas 的最小高度(image wrapper) strict: true, crop: function(e) { //當改變剪裁容器或圖片時的事件函數 console.log(e.detail.x); console.log(e.detail.y); console.log(e.detail.width); console.log(e.detail.height); console.log(e.detail.rotate); console.log(e.detail.scaleX); console.log(e.detail.scaleY); }, build: function () { console.log('build'); }, built: function () { console.log('built'); }, cropstart: function (e) { console.log('cropstart', e.detail.action); }, cropmove: function (e) { console.log('cropmove', e.detail.action); }, cropend: function (e) { console.log('cropend', e.detail.action); } }); $("#btnCrop").on("click", function(){ cropper.setDragMode("crop"); }); $("#btnMove").on("click", function(){ cropper.setDragMode("move"); }); $("#11").on("click", function(){ cropper.setAspectRatio(1,1); }); $("#169").on("click", function(){ cropper.setAspectRatio(16,9); }); $("#getCanvas").on("click", function(){ $("#getCroppedCanvas").html(cropper.getCroppedCanvas()); }); }); </script> </body> </html>
API
https://www.awesomes.cn/repo/fengyuanchen/cropper