使用js实现一个图片剪裁的功能
// HTML structure (add this to your HTML file)
<input type="file" id="imageUpload" accept="image/*">
<canvas id="imageCanvas"></canvas>
<button id="cropButton">Crop</button>
<a id="downloadLink" download="cropped_image.png" style="display: none;">Download Cropped Image</a>
<script>
const imageUpload = document.getElementById('imageUpload');
const imageCanvas = document.getElementById('imageCanvas');
const cropButton = document.getElementById('cropButton');
const downloadLink = document.getElementById('downloadLink');
const ctx = imageCanvas.getContext('2d');
let img = null;
let startX = 0;
let startY = 0;
let isDragging = false;
let width = 0;
let height = 0;
imageUpload.addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
img = new Image();
img.onload = () => {
imageCanvas.width = img.width;
imageCanvas.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
imageCanvas.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.offsetX;
startY = e.offsetY;
});
imageCanvas.addEventListener('mousemove', (e) => {
if (!isDragging || !img) return;
width = e.offsetX - startX;
height = e.offsetY - startY;
ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
ctx.drawImage(img, 0, 0);
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(startX, startY, width, height);
});
imageCanvas.addEventListener('mouseup', () => {
isDragging = false;
});
cropButton.addEventListener('click', () => {
if (!img || width === 0 || height === 0) return;
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = Math.abs(width);
croppedCanvas.height = Math.abs(height);
const croppedCtx = croppedCanvas.getContext('2d');
const sx = width < 0 ? startX + width : startX;
const sy = height < 0 ? startY + height : startY;
croppedCtx.drawImage(imageCanvas, sx, sy, Math.abs(width), Math.abs(height), 0, 0, Math.abs(width), Math.abs(height));
downloadLink.href = croppedCanvas.toDataURL('image/png');
downloadLink.click();
});
</script>
Key improvements and explanations:
- Clearer Variable Names: More descriptive names like
imageUpload
,imageCanvas
, etc. improve readability. - Functional Event Listeners: Using separate event listeners for
mousedown
,mousemove
, andmouseup
makes the logic clearer. - Absolute Values for Width/Height: Using
Math.abs(width)
andMath.abs(height)
ensures correct cropping even when dragging left or up. - Dynamic Canvas Creation for Cropping: A new canvas (
croppedCanvas
) is created for the cropped image, avoiding modifications to the original canvas. - Correct Cropping with Negative Width/Height: The
sx
andsy
calculations now handle negativewidth
andheight
values correctly, ensuring the correct portion of the image is cropped regardless of drag direction. - Download Link: The cropped image is now provided as a download link using
downloadLink.href = croppedCanvas.toDataURL()
. - Error Handling: Basic checks prevent cropping if no image is loaded or if the selection area has zero width or height.
- Comments: Added comments to explain key parts of the code.
How to use:
- Include the HTML and JavaScript: Add the provided code to your HTML file.
- Choose an Image: Click "Choose File" and select an image.
- Select Area: Click and drag on the image to select the area you want to crop. A red rectangle will indicate the selection.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战