JS实现选择图片剪裁及保存
以下是一个简单的示例代码,实现了显示一个文件上传框和一个canvas元素。用户可以选择一张图片文件后,该图像将显示在canvas中,并且用户可以通过鼠标拖拽来选取需要剪裁的区域。单击“剪裁”按钮,程序会将结果保存为新的图片文件并在浏览器中下载。
先看效果图:
源码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS图片剪裁并保存</title>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border:1px solid #000;"></canvas>
<div>
<input type="file" id="fileInput">
<button id="cropButton" disabled>剪裁</button>
用户可以拖动鼠标来选择需要剪裁的区域
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let image = null;
let isDragging = false;
let startX = 0;
let startY = 0;
let endX = 0;
let endY = 0;
// 加载图片
const loadImage = (file) => {
const reader = new FileReader();
reader.onload = (e) => {
image = new Image();
image.onload = () => {
ctx.drawImage(image, 0, 0);
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
disableButtons(); //
};
// 监听文件上传事件
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
loadImage(file);
});
// 监听鼠标事件,绘制选择区域
canvas.addEventListener('mousedown', (e) => {
if (isDragging) return;
isDragging = true;
startX = e.offsetX;
startY = e.offsetY;
endX = startX;
endY = startY;
});
canvas.addEventListener('mousemove', (e) => {
if (!isDragging) return;
endX = e.offsetX;
endY = e.offsetY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(startX, startY, endX - startX, endY - startY);
});
canvas.addEventListener('mouseup', () => {
isDragging = false;
if (endX > startX && endY > startY) {
enableButtons();
}
});
// 监听确定按钮点击事件,剪裁并保存图片
const cropButton = document.getElementById('cropButton');
cropButton.addEventListener('click', () => {
disableButtons();
const croppedCanvas = document.createElement('canvas');
const croppedCtx = croppedCanvas.getContext('2d');
const width = endX - startX;
const height = endY - startY;
croppedCanvas.width = width;
croppedCanvas.height = height;
croppedCtx.drawImage(canvas, startX, startY, width, height, 0, 0, width, height);
const url = croppedCanvas.toDataURL();
const link = document.createElement('a');
link.download = 'cropped-image.png';
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
// 激活按钮
const enableButtons = () => {
cropButton.disabled = false;
};
// 禁用按钮
const disableButtons = () => {
cropButton.disabled = true;
};
</script>
</body>
</html>
OK!