两个主要的问题解决:
如何实现本地预览?
只需要上传图片生成base64的格式,然后挂载到dom上就可以了。
如何实现图像部分的上传?
使用canvas进行画出裁剪完的图片即可。
具体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片裁剪</title>
</head>
<body>
<input type="file"/>
<img class="preview" alt="" src=""/>
<button>生成截图后的file对象</button>
<script>
const ipt = document.querySelector('input[type=file]');
const preview = document.querySelector('.preview');
const button = document.querySelector('button');
ipt.onchange = function(e) {
const file = e.target.files[0];
console.log(file)
const reader = new FileReader();
reader.onload =(e)=>{
console.log(e.target.result);
preview.src = e.target.result;
};
reader.readAsDataURL(file);
}
button.onclick = function() {
//进行裁剪: 裁剪我们需要在原图的裁剪坐标,原图中裁剪的宽高,裁剪后的缩放尺寸也就是宽高
//我们如果想要定位裁剪的位置,需要知道四个参数,原图的宽高,以及裁剪的x和y坐标。
const cutInfo = {
//要裁剪的坐标
x:300,
y:200,
//原图尺寸
cutWidth:300,
cutHeight:300,
//裁剪完缩放的尺寸
width:100,
height:100,
}
//生成canvas
const canvas = document.createElement('canvas');
canvas.width = cutInfo.width;
canvas.height = cutInfo.height;
const ctx = canvas.getContext('2d');
// 下面的两个0,0 是把图片画到canvas中的位置,就是靠左靠上。
ctx.drawImage(preview, cutInfo.x, cutInfo.y,cutInfo.width,cutInfo.height, 0, 0,cutInfo.width,cutInfo.height);
//canvas方法,转成二进制
canvas.toBlob((blob)=>{
//blob转换成 File
const file = new File([blob], 'avatar.jpeg', {type: 'image/jpeg'});
console.log(file);
//使用ajax 上传到服务器即可
},'image/jpeg');
document.body.appendChild(canvas);
}
</script>
</body>
</html>