一、效果预览
二、实现
1、引入文件:jquery.js, cropper.min.css,ImgCropping.css,cropper.min.js等,文件下载地址:http://www.jq22.com/jquery-info18167
2、裁剪图片的弹框
<div style="display: none" class="tailoring-container" id="tailoring-container">
<div class="black-cloth" onclick="closeTailor(this)"></div>
<div class="tailoring-content">
<div class="tailoring-content-one">
<div class="close-tailoring" onclick="closeTailor(this)">×</div>
</div>
<div class="tailoring-content-two">
<div class="tailoring-box-parcel">
<img id="tailoringImg">
</div>
<div class="preview-box-parcel">
<p>图片预览:</p>
<div class="square previewImg"></div>
<!-- <div class="circular previewImg"></div>-->
</div>
</div>
<div class="tailoring-content-three">
<button type="button" class="l-btn cropper-reset-btn">复位</button>
<button type="button" class="l-btn cropper-rotate-lef-btn">向右旋转</button>
<button type="button" class="l-btn cropper-rotate-right-btn">向左旋转</button>
<button type="button" class="l-btn cropper-big-btn">放大</button>
<button type="button" class="l-btn cropper-small-btn">缩小</button>
<button type="button" class="l-btn sureCut" id="sureCut" @@click="confirmCutImg">确定</button>
</div>
</div>
</div>
</template>
</div>
3、初始化
// cropper图片裁剪
$('#tailoringImg').cropper({
...this.cutObj,
crop : function(e) {
// 输出结果数据裁剪图像。
}
});
4、选择文件时调用以下代码
$(".tailoring-container").toggle();
var reader = new FileReader();
reader.onload = function(evt) {
var replaceSrc = evt.target.result;
// 更换cropper的图片
$('#tailoringImg').cropper('replace', replaceSrc, false);// 默认false,适应高度,不失真
flag = true
}
reader.readAsDataURL(file);
5、点击弹框的确定按钮 调用以下代码
if ($("#tailoringImg").attr("src") == null) {
return false;
} else {
var cas = $('#tailoringImg').cropper('getCroppedCanvas');// 获取被裁剪后的canvas
var base64 = cas.toDataURL('image/jpeg'); // 转换为base64
//这里去做上传操作
//uploadfile(base64)
closeTailor();// 关闭裁剪框
}
6、其他功能函数 放大、缩小、旋转、复位等
// 向左旋转
$(".cropper-rotate-lef-btn").on("click", function() {
$('#tailoringImg').cropper("rotate", 45);
});
//向右旋转
$(".cropper-rotate-right-btn").on("click", function() {
$('#tailoringImg').cropper("rotate", -45);
});
//放大
$(".cropper-big-btn").on("click", function() {
$('#tailoringImg').cropper('zoom', 0.1);
});
//缩小
$(".cropper-small-btn").on("click", function() {
$('#tailoringImg').cropper('zoom', -0.1);
});
// 复位
$(".cropper-reset-btn").on("click", function() {
$('#tailoringImg').cropper("reset");
});
// 关闭裁剪框
function closeTailor() {
$(".tailoring-container").toggle();
}