图片裁剪插件(github上最多用户使用完美版)

发表于 2020-07-23 17:05:29   |   下载附件   |   字体:
Cropper.js图片裁剪图片上传独立裁剪插件

电脑上实例图

手机端实例图


html

<div class="container">
    <h1>
        Customize preview for Cropper
    </h1>
    <p><span id="reset" class="btn">重设</span> <span id="destroy" class="btn">销毁</span></p>
    <div class="row">
        <div class="col col-lt">
            <img id="image" src="images/003.jpg" alt="Picture"/>
        </div>
        <div class="col col-rt">
            <div class="preview">
                <img src="images/003.jpg" alt="Picture"/>
            </div>
        </div>
    </div>
</div>


js

// 裁剪对象
var cropper;
// 裁剪参数
var options = {
    dragMode: 'move',
    preview: '.preview',
    aspectRatio: 1 / 1,
    viewMode: 2,
    ready: function (e) {
        console.log(e.type);
        // 准备好了
        previewReady = true;
    },
    crop: function (e) {
        if (!previewReady) {
            return;
        }
        var data = e.detail;
        var cropper = this.cropper;
        var imageData = cropper.getImageData();
        var previewAspectRatio = data.width / data.height;
        console.log(e);
        // 上传裁剪参数
        var temp = {}
        temp.dataX = Math.round(data.x);
        temp.dataY = Math.round(data.y);
        temp.dataHeight = Math.round(data.height);
        temp.dataWidth = Math.round(data.width);
        temp.dataRotate = typeof data.rotate !== 'undefined' ? data.rotate : '';
        temp.dataScaleX = typeof data.scaleX !== 'undefined' ? data.scaleX : '';
        temp.dataScaleY = typeof data.scaleY !== 'undefined' ? data.scaleY : '';
        console.log(temp);
    },
    cropstart: function (e) {
      console.log(e.type, e.detail.action);
    },
    cropmove: function (e) {
      console.log(e.type, e.detail.action);
    },
    cropend: function (e) {
      console.log(e.type, e.detail.action);
    },
    zoom: function (e) {
      console.log(e.type, e.detail.ratio);
    }
}

// 初始化事件绑定
window.addEventListener('DOMContentLoaded', function () {
    var image = document.querySelector('#image');
    var previews = document.querySelectorAll('.preview');
    var previewReady = false;
    // 实例化裁剪对象
    cropper = new Cropper(image, options);
});

// 销毁
document.getElementById('destroy').addEventListener('click', function () {
    cropper.destroy();
});

// 重设
document.getElementById('reset').addEventListener('click', function () {
    var image = document.querySelector('#image');
    var previews = document.querySelectorAll('.preview');
    var previewReady = false;
    // 实例化裁剪对象
    cropper = new Cropper(image, options);
});