需求:上传头像,截取大小
cropper版本:4.0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
</head>
<link rel="stylesheet" href="lib/cropper.css">
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="lib/cropper.js"></script>
<style>
html,body{margin:0;padding:0;}
</style>
<body>
<input type="file" id="file" accept="image/*">
<div style="width:100%;max-height:300px;" id="image_div"> <!--这里注意,直接设置img
的宽高是没有效果的,但是可以在父div设置;-->
<img id="img" src="" >
</div>
<img id="img_base64" src="" style="width:200px;height:200px;display:none">
<button id="ok_id">确定</button>
<script>
var $image = $('#img_base64');
$('#file').change(function(e){
var file;
var files = e.target.files;
if (files && files.length > 0) {
file = URL.createObjectURL(files[0]);
$('#img').attr({'src': file})
}
$('#img').cropper("destroy");
$('#img').cropper({
aspectRatio: 1,
viewMode: 1,
guides: false, //是否显示裁剪框虚线
crop: function (e) { //剪裁框发生变化执行的函数。
}
});
})
$("#ok_id").on("click",function(){
var dataURL = $('#img').cropper("getCroppedCanvas"); //cropper自带方法
var imgurl = dataURL.toDataURL("image/*", 0.5); //canvas转base64格式
$image.attr('src', imgurl);
$image.show();
})
</script>
</body>
</html>
参考资料:
https://blog.csdn.net/weixin_38023551/article/details/78792400