文本内容
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.7/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.7/cropper.css" />
<div class="box" onclick="selectImageBindtap()">
<img id="image" src="">
</div>
<div class="box1">
<img class="img" src="" alt="">
</div>
<input
type="file"
id="image1"
style="display:none"
value="aaa"
onchange="imgChange(this)">
<button onclick="cropperBindtap()">裁剪</button>
<button onclick="reset()">重置</button>
简单修饰
.box {
width: 600px;
min-height: 300px;
background: rgba(0, 0, 0, .3);
}
#image, .img {
display: block;
max-width: 100%;
}
.box1 {
width: 300px;
}
相关js
var cropper;
var image = document.getElementById('image');
function selectImageBindtap () {
console.log(1)
$('#image').attr('src', '');
console.log($('#image1'));
$('#image1').click()
};
function imgChange (img) {
console.log(img);
console.log(img.files)
var reader = new FileReader();
reader.readAsDataURL(img.files[0]);
reader.onload = function(e) {
var imgBase64Data = e.target.result;
console.info(imgBase64Data);
$('#image').attr('src', imgBase64Data);
cropperFun(imgBase64Data);
}
}
function cropperFun(imgBase64Data) {
console.log(image);
cropper = new Cropper(image, {
viewMode:1,
dragMode:'none',
initialAspectRatio: 1,
preview: '.before',
background: true,
autoCropArea: 0.6,
})
image.cropper.replace(imgBase64Data);
}
cropperBindtap = function () {
let baseUrl = image.cropper.getCroppedCanvas({
imageSmoothingQuality: 'high'
}).toDataURL('image/jpeg')
$('.img').attr('src', '');
$('.img').attr('src', baseUrl);
dataURLtoFile(baseUrl, 'asdasdas')
}
function dataURLtoFile (baseUrl, fileName) {
var arr = baseUrl.split(','),
mime = arr[0].match(/:(.*?);/)[1];
var extension = mime.split('/')[1];
var bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], fileName + '.' + extension, { type: mime });
}
裁剪前
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fb629f2b9cc27c2f4ffb104a055c43f5.png#pic_center)
裁剪后
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5b1e929f14796a8621e0cdb68b0403e8.png#pic_center)