英文文档(较全,比较新)https://github.com/fengyuanchen/cropperjs/blob/master/README.md
源码下载:https://github.com/fengyuanchen/cropperjs小 demo:
1.引入cropper的css,js文件
<link rel="stylesheet" href="/kadmin/zlmm/static/cropperjs/cropper.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><!--可不引(便于使用)-->
<script src="/kadmin/zlmm/static/cropperjs/cropper.js"></script> <!--修改为存放地址-->
2.显示(填充)图片资源,便于被js获取
<div class="col col-6">
<img id="image" src="<?php echo $src; ?>" alt="Picture"> <!--图片资源有外界传入,练习时用固定图片比较好-->
</div>
...
<button class="layui-btn" id="crop">确定</button><!--确认裁剪-->
3.js监听裁剪图片
window.addEventListener('DOMContentLoaded', function () {
var image = document.querySelector('#image');
var previews = document.querySelectorAll('.preview');
var $alert = $('.alert');
cropper = new Cropper(image, {
scalable:false, //参数 由需求自定义
zoomable:false,
background:false,
viewMode:1,
aspectRatio:ratio, //裁剪框比例设置动态改变的,由外界参数决定(单独使用可设置常量)
checkCrossOrigin:false,
checkImageOrigin:false,
dragCrop:false,
modal:false,
dragMode:'move',
movable:false
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
if (cropper) {
canvas = cropper.getCroppedCanvas({});
initialAvatarURL = image.src;
pic_data = canvas.toDataURL();
// canvas.toBlob(function (blob) { 报错
// var formData = new FormData();
// formData.append('file', blob, 'cropper.jpg');
// formData.append('category','bbs_post_recom/cropper');
// });
//调用自定义方法处理 canvas.toBlob() 失败事件
blob = processData(pic_data);//自定义方法解决canvas.toBlob() 失败
var formData = new FormData();
formData.append('file', blob, 'cropper.jpg');
formData.append('category','bbs_post_recom/cropper');
$.ajax('pic_upload', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
da = JSON.parse(data);
if(da.ret == 1){ //保存成功后的操作
.....
}else{
alert(da.msg);
}
},
error: function (data) {
image.src = initialAvatarURL;
},
complete: function () {
},
});
}
});
});
方法来自:https://blog.csdn.net/github_38854224/article/details/86741601