需求描述:
移动端拍摄照片后,弹出图片裁剪窗口,支持图片缩放、移动、旋转,将裁剪后的图片以base64的格式传给后端。
一、引入cropper.js
git地址:https://github.com/fengyuanchen/cropperjs
<link rel="stylesheet" href="../../cropper.min.css">
<script src="../../jquery.min.js"></script>
<script src="../../cropper.min.js"></script>
二、html代码
<div class="upload-img">
<input id="selectImg" type="file" accept="image/*" capture="camera" >
</div>
<!-- 裁剪图片弹窗 -->
<div class="model cut-img-model" style="display: none;">
<div class="model-content">
<div class="cut-img-box">
<img id="cropperImg">
</div>
<p class="instructions">拖动底部照片调整大小,将人脸放入人脸框中</p>
<div class="btnGroup flex-sb">
<div id="cancel">取消</div>
<div id="rotate">旋转</div>
<div id="crop">保存</div>
</div>
</div>
</div>
css代码
// 限制图片最大宽度,避免超出外层容器,必须!
#cropperImg {
max-width: 100%;
}
// 人形裁剪框可通过以下设置背景图实现
.cropper-view-box,
.cropper-face {
background:url('../../img/cut.png') no-repeat;
background-size: 100%;
opacity: 1;
}
js代码
初始化
1、裁剪框固定且不可放大缩小
var image = document.querySelector('#cropperImg');
var cropper = new Cropper(image, {
dragMode: 'move',
aspectRatio: 1,
autoCropArea: 0.9,
restore: false,
guides: false,
center: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
});
2、图片铺满整个裁剪区域
var image = document.querySelector('#image');
var cropper = new Cropper(image, {
viewMode: 3,
dragMode: 'move',
autoCropArea: 1, // 可设置裁剪框的范围,为1则是与整个裁剪区域一样大
restore: false,
modal: false,
guides: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
});
选取图片
$('#selectImg').on('change',function(e){
var file = e.target.files[0];
$(".cut-img-model").toggle();
var reader = new FileReader();
reader.onload = function(evt) {
var replaceSrc = evt.target.result;
// 更换cropper的图片
cropper.replace(replaceSrc, false);
}
reader.readAsDataURL(file);
})
旋转
$('#rotate').on('click', function() {
cropper.rotate(90);
})
裁剪
$('#crop').on('click', function() {
$(".cut-img-model").toggle();
var src = cropper.getCroppedCanvas().toDataURL('image/jpeg', 0.7);
console.log(src); // base64格式
})
参考资料:https://www.cnblogs.com/eightFlying/p/cropper-demo.html
https://blog.csdn.net/achejq/article/details/93240104