1.引入cropper.js插件的CSS和JS文件
<link rel="stylesheet" href="cropper.css"><script src="cropper.js"></script>
<script src="cropper.js"></script>
2.在HTML中添加一个图片元素和一个裁剪框元素
<img id="image" src="image.jpg">
<div id="cropper"></div>
3.初始化cropper对象
var cropper = new Cropper(document.getElementById('image'),
{
aspectRatio: 16 / 9,
viewMode: 1,
crop: function(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
}
}
);
4.可选:设置cropper对象的属性
var cropper = new Cropper();
cropper.setData({
x: 100,
y: 100,
width: 200,
height: 200,
rotate: 45,
scaleX: 1,
scaleY: 1
});
5.可选:获取裁剪后的图片数据
var cropper = new Crooper()
cropper.getCroppedCanvas().toDataURL();
6.可选:销毁cropper对象
var cropper = new Crooper()
cropper.destroy();
初始化cropper对象时,可以设置以下属性值:
aspectRatio: 裁剪框的宽高比,默认为自由比例
autoCropArea: 自动裁剪区域的大小,百分比或像素值,默认为0.8(即裁剪框的宽高比的80%)
background: 裁剪框外的背景色,默认为白色
cropBoxMovable: 是否允许移动裁剪框,默认为true
cropBoxResizable: 是否允许调整裁剪框大小,默认为true
crop: 裁剪框的初始位置和大小
data: 图片的初始位置和大小
dragMode: 鼠标拖动的模式,可选值为crop(裁剪模式)和move(移动模式),默认为crop
guides: 是否显示裁剪框辅助线,默认为true
minCanvasHeight: 画布的最小高度,默认为0
minCanvasWidth: 画布的最小宽度,默认为0
minContainerHeight: 容器的最小高度,默认为0
minContainerWidth: 容器的最小宽度,默认为0
minCropBoxHeight: 裁剪框的最小高度,默认为0
minCropBoxWidth: 裁剪框的最小宽度,默认为0
modal: 是否显示模态框,默认为true
movable: 是否允许移动图片,默认为true
preview: 预览图的容器,可以是CSS选择器、HTML元素或jQuery对象
responsive: 是否启用响应式布局,默认为true
restore: 是否允许重置裁剪框和图片位置,默认为true
rotatable: 是否允许旋转图片,默认为true
scalable: 是否允许缩放图片,默认为true
toggleDragModeOnDblclick: 是否启用双击切换拖动模式,默认为true
viewMode: 显示模式,可选值为0(自由模式)、1(包含裁剪框的模式)和2(只显示裁剪框的模式),默认为0。
以上属性值可以通过传递一个配置对象来设置,例如:
var cropper = new Cropper(image, {
aspectRatio: 16 / 9,
autoCropArea: 0.8,
background: false,
cropBoxMovable: false,
cropBoxResizable: false,
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);
},
data: { x: 0, y: 0, width: 640, height: 480 },
dragMode: 'move',
guides: false,
minCropBoxHeight: 100,
minCropBoxWidth: 100,
preview: '.preview',
responsive: true,
restore: false,
rotatable: false,
scalable: false,
toggleDragModeOnDblclick: false,
viewMode: 1
});
以下是移动端裁剪案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.12/cropper.min.css">
<script src="https://cdn.bootcdn.net/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
<script src="./bootstrap/js/jquery-3.5.0.min.js"></script>
<style>
.addImage {
height: 20px;
line-height: 20px;
text-align: center;
padding: 20px;
width: fit-content;
background-color: antiquewhite;
}
.box {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
background-color: #1e1e1e;
}
.center {
position: absolute;
top: 45%;
left: 0;
transform: translate(0, -50%);
width: 100vw;
height: 60vh;
overflow: hidden;
}
.copperMainBox {
width: 100%;
height: 100%;
}
.btn-box {
position: absolute;
bottom: 0;
left: 0;
width: 100vw;
display: flex;
justify-content: space-between;
}
.btn {
background-color: #1e1e1e;
width: fit-content;
padding: 5px 25px;
border: 1px solid rgb(182, 182, 182);
border-radius: 5px;
margin: 0 20px 10px 20px;
color: #fff;
}
</style>
</head>
<body>
<div class="addImage">
点击添加图片
</div>
<div id="showTailorImage"></div>
<div class="box">
<div class="center">
<div class="copperMainBox"><img src="" alt="" id="image"></div>
</div>
<div class="btn-box">
<div class="btn" id="cancelTailor">取消</div>
<div class="btn" id="affirmTailor">确认</div>
</div>
<input type="file" name="imageFile" id="chooseLogoImg" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
value="" style="display: none;" />
</div>
</body>
<script>
$(".box").hide()
let cropper = null
$(".addImage").click(function () {
$("#chooseLogoImg").click()
})
$("#chooseLogoImg").change(function (e) {
var chooseImgUrl = URL.createObjectURL($(this)[0].files[0])
$(".box").show()
$('#image').attr('src', chooseImgUrl);
if (!cropper) {
cropper = new Cropper(image, {
aspectRatio: 0.5 / 0.7,
autoCropArea: 0.8,
background: false,
cropBoxMovable: false,
cropBoxResizable: false,
dragMode: 'move',
guides: false,
minCropBoxHeight: 200,
minCropBoxWidth: 200,
responsive: true,
restore: false,
rotatable: false,
scalable: false,
toggleDragModeOnDblclick: false,
viewMode: 1
});
} else {
cropper.reset().replace(chooseImgUrl);
}
})
//取消裁剪
$('#cancelTailor').click(function () {
$('#chooseLogoImg').val(''); //清空input file val值 选择相同图片 change的bug,
$('.box').hide();
})
//确定裁剪
$("#affirmTailor").click(function () {
//生成canvas
let canvasImage = cropper['getCroppedCanvas']({ minWidth: 200, maxHeight: 200 })
//展示 canvas
$("#showTailorImage").append(canvasImage)
//拿到input 选择file的名字
let fileName = $("#chooseLogoImg").val().split("\\").slice(-1)[0]
//清空 input file 的value
$("#chooseLogoImg").val("")
// 转 file 文件格式
const dataURL = canvasImage.toDataURL('image/png')
const blob = dataURLtoBlob(dataURL);
const file = new File([blob], fileName, { type: 'image/png' });
//隐藏裁剪框
$(".box").hide();
})
//转二进制 file
function dataURLtoBlob(dataURL) {
const arr = dataURL.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
//以下内容放到外部 dataURL :base64
// const blob = dataURLtoBlob(dataURL);
// const file = new File([blob], 'myImage.png', { type: 'image/png' });
}
// cropper.setData({ x: 100, y: 100, width: 200, height: 200, rotate: 45, scaleX: 1, scaleY: 1});
</script>
</html>