JavaScript 图片剪切通常涉及到 HTML5 的 Canvas API 和一些 JavaScript 代码来实现。以下是一个简单的图片剪切源码示例,它允许用户通过拖拽选择图片的一部分进行剪切:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片剪切</title>
<style>
#imageCanvas {
border: 1px solid black;
}
#selectionBox {
position: absolute;
border: 1px dashed red;
background-color: rgba(255, 255, 255, 0.5);
cursor: move;
}
</style>
</head>
<body>
<canvas id="imageCanvas" width="500" height="500"></canvas>
<div id="selectionBox"></div>
<img id="originalImage" src="your-image-url.jpg" style="display:none;">
<script>
const canvas = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
const originalImage = document.getElementById('originalImage');
const selectionBox = document.getElementById('selectionBox');
let isDragging = false;
let startX, startY, endX, endY;
originalImage.onload = () => {
ctx.drawImage(originalImage, 0, 0);
};
canvas.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.offsetX;
startY = e.offsetY;
selectionBox.style.left = `${startX}px`;
selectionBox.style.top = `${startY}px`;
selectionBox.style.width = '0px';
selectionBox.style.height = '0px';
});
canvas.addEventListener('mousemove', (e) => {
if (!isDragging) return;
endX = e.offsetX;
endY = e.offsetY;
selectionBox.style.width = `${Math.abs(endX - startX)}px`;
selectionBox.style.height = `${Math.abs(endY - startY)}px`;
selectionBox.style.left = `${Math.min(startX, endX)}px`;
selectionBox.style.top = `${Math.min(startY, endY)}px`;
});
canvas.addEventListener('mouseup', () => {
isDragging = false;
cropImage();
});
function cropImage() {
const width = Math.abs(endX - startX);
const height = Math.abs(endY - startY);
const x = Math.min(startX, endX);
const y = Math.min(startY, endY);
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = width;
croppedCanvas.height = height;
const croppedCtx = croppedCanvas.getContext('2d');
croppedCtx.drawImage(canvas, x, y, width, height, 0, 0, width, height);
// 这里可以将 croppedCanvas.toDataURL() 的结果用于显示或上传剪切后的图片
console.log(croppedCanvas.toDataURL());
}
</script>
</body>
</html>onload 事件。对于图片加载延迟的问题,可以在 originalImage.onload 事件触发后再执行绘制操作,确保图片已经完全加载。
originalImage.onload = () => {
ctx.drawImage(originalImage, 0, 0);
};对于剪切区域超出图片边界的问题,可以在计算剪切区域时加入边界检查:
function cropImage() {
const width = Math.abs(endX - startX);
const height = Math.abs(endY - startY);
const x = Math.min(startX, endX);
const y = Math.min(startY, endY);
if (x + width > canvas.width || y + height > canvas.height) {
alert('剪切区域超出了图片边界!');
return;
}
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = width;
croppedCanvas.height = height;
const croppedCtx = croppedCanvas.getContext('2d');
croppedCtx.drawImage(canvas, x, y, width, height, 0, 0, width, height);
console.log(croppedCanvas.toDataURL());
}以上代码提供了一个基本的图片剪切功能,可以根据具体需求进行扩展和优化。
没有搜到相关的沙龙