实现原理
- 借助canvas画布, 实现对上传图片进行裁切
- 核心方法
// context表示canvas画布上下文对象
context.drawImage(图片对象,裁切起始点x坐标,裁切起始点y坐标,裁切宽度,裁切高度,绘制起始点x坐标,绘制起始点y坐标,绘制宽度,绘制高度)
-
注意事项:
- 需要计算图片原始尺寸和图片显示尺寸的比例
- 裁切宽度和裁切高度, 需要结合元素图片的宽高决定, 而不是img标签的宽高, 需要根据图片的实际尺寸和显示尺寸比例关系进行转换
- 裁切起始点的坐标要根据图片的实际尺寸和显示尺寸之间的比例关系进行换算
实现代码
<!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>
<style>
.upload {
border: 1px solid #CCC;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
font-size: 50px;
color: #CCC;
font-weight: normal;
cursor: pointer;
display: none;
}
.preview-wrap {
position: relative;
border: 1px solid #EEE;
height: 300px;
width: 300px;
margin: 10px 0;
cursor: move;
overflow: hidden;
display: none;
}
.preview {
position: relative;
width: 100%;
height: auto;
border: 1px solid #EEE;
transition: all 0.2s;
}
.mask {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 160px;
height: 160px;
z-index: 999;
cursor: move;
/* box-shadow: 0 0 0 10px rgb(0,0,0,0.5); */
box-shadow: 0 0 0 70px rgb(0 0 0 / 50%);
user-select: none;
}
.clip-preview {
display: none;
}
.visible {
display: block;
}
</style>
</head>
<body>
<div class="avatar">
<!-- 选择图片按钮 -->
<div class="upload visible">
十
</div>
<div class="preview-wrap">
<!-- 遮罩 -->
<div class="mask"></div>
<!-- 原图预览 -->
<img class="preview">
</div>
<!-- 裁切结果预览 -->
<img class="clip-preview" alt="">
<button class="reselect">重新选择</button>
<button class="upload-btn">上传</button>
</div>
<!-- 文件域 -->
<input type="file" accept="image/png,image/jpeg,image/gif" id="file" style="display: none;">
<script>
const file = document.querySelector('#file');
const upload = document.querySelector('.upload');
const preview = document.querySelector('.preview');
const mask = document.querySelector('.mask');
const wrap = document.querySelector('.preview-wrap');
const reselect = document.querySelector('.reselect');
const clip = document.querySelector('.clip-preview');
const uploadBtn = document.querySelector('.upload-btn');
// 裁切起始点的坐标
let clipStartX = clipStartY = 70;
// 图片原始尺寸和显示尺寸的比例, 默认为1:1
let scaleX = scaleY = 1;
// 裁切后的而图片文件文件
let avatarFile;
// 根据裁切尺寸在canvas画布中绘制图片
function draw() {
// 创建canvas标签
const canvas = document.createElement('canvas');
canvas.width = 160;
canvas.height = 160;
const context = canvas.getContext('2d');
// 对图片进行裁切, 将裁切内容绘制到画布中
context.drawImage(preview, clipStartX * scaleX, clipStartY * scaleY, 160 * scaleX, 160 * scaleY, 0, 0, 160,
160);
// 将canvas转化为blob
canvas.toBlob((blob) => {
// console.log(URL.createObjectURL(blob));
avatarFile = new File([blob], "avatar.png", {
type: "image/png"
});
})
clip.src = canvas.toDataURL();
clip.classList.add('visible');
}
upload.addEventListener('click', function () {
file.click();
});
reselect.addEventListener('click', function () {
upload.classList.add('visible');
wrap.classList.remove('visible');
clip.classList.remove('visible');
file.click();
});
file.addEventListener('change', function () {
if (!file.files[0]) {
return false;
}
// 获取图片文件对象
const fileData = file.files[0];
// 创建fileReader实例
const fileReader = new FileReader();
fileReader.readAsDataURL(fileData);
fileReader.onload = function (e) {
const img = new Image();
img.src = e.target.result;
img.addEventListener('load', function () {
// 计算图片原始尺寸和显示尺寸之间的比例
scaleX = img.width / 300;
scaleY = img.height / 300;
// 初次绘制裁切结果
draw();
});
// 设置图片Url
preview.src = e.target.result;
// 显示预览图
wrap.classList.add('visible');
upload.classList.remove('visible');
}
});
// 鼠标按键状态
let mouseState = false;
// 记录鼠标指针起始位置
let startX = startY = 0;
// 监听鼠标按键按下状态
wrap.addEventListener('mousedown', event => {
// 更新鼠标状态
mouseState = true;
const {
offsetX,
offsetY
} = event;
startX = offsetX;
startY = offsetY;
});
wrap.addEventListener('mousemove', event => {
const {
offsetX,
offsetY
} = event;
if (!mouseState) {
return false;
}
// 计算鼠标指针移动距离
let distanceX = offsetX - startX;
let distanceY = offsetY - startY;
// 移动图片
if (preview.offsetLeft + distanceX < 70 && preview.offsetLeft + distanceX > -70) {
preview.style.left = (preview.offsetLeft + distanceX) + 'px';
}
if (preview.offsetTop + distanceY < 70 && preview.offsetTop + distanceY > -70) {
preview.style.top = (preview.offsetTop + distanceY) + 'px';
}
// 更新裁切起始点的坐标信息
clipStartX = 70 - preview.offsetLeft;
clipStartY = 70 - preview.offsetTop;
// 重新绘制裁切图片
draw();
});
// 鼠标按键抬起, 更新鼠标按键状态
document.addEventListener('mouseup', function () {
mouseState = false;
});
uploadBtn.addEventListener('click', function () {
if (!avatarFile) {
alert('请选择图片');
}
// 将文件对象发送给后端数据接口即可
console.log(avatarFile);
});
</script>
</body>
</html>