前言
流程如下:本地预览 => 裁剪 => 上传
实现
1. 本地预览
将数据读为 dataurl
赋值给 img 标签的 src
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
display: flex;
}
#image-container {
position: relative;
width: 400px;
height: 400px;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
#result {
margin-left: 20px;
border: 1px solid #ccc;
width: 200px;
height: 200px;
background-color: #f3f3f3;
}
</style>
</head>
<body>
<div>
<input type="file" id="file-input">
</div>
<div class="container">
<div id="image-container">
<img id="uploaded-image" style="width: 100%; height: 100%;" />
</div>
<canvas id="result" width="200" height="200"></canvas> <!-- 显示裁剪结果的画布 -->
</div>
<script>
const fileInput = document.getElementById('file-input');
const uploadedImage = document.getElementById('uploaded-image');
fileInput.onchange = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
uploadedImage.src = e.target.result;
}
reader.readAsDataURL(file);
}
</script>
</body>
</html>
2. 裁剪
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片裁剪预览</title>
<style>
.container {
display: flex;
}
#image-container {
position: relative;
width: 400px;
height: 400px;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
#crop-box {
position: absolute;
border: 2px dashed #ff0000;
cursor: move;
display: none;
}
#crop-box .resize-handle {
position: absolute;
width: 10px;
height: 10px;
background: #ff0000;
z-index: 10;
}
#crop-box .top-left {
left: -5px;
top: -5px;
cursor: nwse-resize;
}
#crop-box .top-right {
right: -5px;
top: -5px;
cursor: nesw-resize;
}
#crop-box .bottom-left {
left: -5px;
bottom: -5px;
cursor: nesw-resize;
}
#crop-box .bottom-right {
right: -5px;
bottom: -5px;
cursor: nwse-resize;
}
#result {
margin-left: 20px;
border: 1px solid #ccc;
width: 200px;
height: 200px;
background-color: #f3f3f3;
}
</style>
</head>
<body>
<div>
<input type="file" id="file-input">
</div>
<div class="container">
<div id="image-container">
<img id="uploaded-image" style="max-width: 100%; max-height: 100%; display: none;" />
<div id="crop-box">
<div class="resize-handle top-left"></div> <!-- 左上角调整手柄 -->
<div class="resize-handle top-right"></div> <!-- 右上角调整手柄 -->
<div class="resize-handle bottom-left