本文將詳細介紹一個基于 HTML 和 JavaScript 實現的圖片裁剪上傳功能。該功能支持文件選擇、拖放上傳、圖片預覽、區域選擇、裁剪操作以及圖片下載等功能,適用于需要進行圖片處理的 Web 應用場景。
效果演示
項目概述
本項目主要包含以下核心功能:
- 文件選擇與拖放上傳
- 裁剪框拖動與調整大小
- 圖片裁剪
- 圖片上傳(模擬)與下載
頁面結構
上傳區域
實現友好的文件選擇體驗,并支持拖放上傳。
<div class="upload-section"><input type="file" id="fileInput" accept="image/*"><label for="fileInput" class="file-label">選擇圖片</label><p>或拖放圖片到此處</p>
</div>
預覽區域
分為兩個部分,左側顯示原始圖片和裁剪框,右側展示裁剪后的結果。
<div class="preview-section"><div class="image-container"><div><h3>原始圖片</h3><img id="originalImage" style="max-width: 100%; display: none;"><div class="cropper-container" id="cropperContainer" style="display: none;"><canvas id="sourceCanvas"></canvas><div class="selection-box" id="selectionBox"><div class="resize-handle"></div></div></div><p class="instruction">拖動選擇框可移動位置,拖動右下角可調整大小</p></div><div><h3>裁剪結果</h3><canvas id="croppedCanvas" style="display: none;"></canvas><p id="noCropMessage">請先選擇圖片并設置裁剪區域</p></div></div>
</div>
操作按鈕
提供“裁剪”、“上傳”、“下載”和“重置”按鈕,方便用戶進行各種操作。
<div class="controls"><button id="cropBtn" disabled>裁剪圖片</button><button id="uploadBtn" disabled>上傳圖片</button><button id="downloadBtn" disabled>下載圖片</button><button id="resetBtn">重置</button>
</div>
核心功能實現
定義基礎變量
獲取DOM元素
const fileInput = document.getElementById('fileInput');
const originalImage = document.getElementById('originalImage');
const sourceCanvas = document.getElementById('sourceCanvas');
const croppedCanvas = document.getElementById('croppedCanvas');
const cropperContainer = document.getElementById('cropperContainer');
const selectionBox = document.getElementById('selectionBox');
const cropBtn = document.getElementById('cropBtn');
const uploadBtn = document.getElementById('uploadBtn');
const resetBtn = document.getElementById('resetBtn');
const noCropMessage = document.getElementById('noCropMessage');
const downloadBtn = document.getElementById('downloadBtn');
定義全局變量
let isDragging = false;
let isResizing = false;
let startX, startY;
let selection = {x: 0,y: 0,width: 0,height: 0,startX: 0,startY: 0,startWidth: 0,startHeight: 0
};
let imageRatio = 1;
文件選擇
使用 FileReader API 將選中的圖片讀取為 Data URL 并顯示在頁面上。
function handleFileSelect(event) {const file = event.target.files[0];if (!file || !file.type.match('image.*')) {alert('請選擇有效的圖片文件');return;}const reader = new FileReader();reader.onload = function(e) {originalImage.src = e.target.result;originalImage.onload = function() {initCropper();};};reader.readAsDataURL(file);
}
拖放上傳
通過監聽 dragover、dragleave 和 drop 事件實現拖放上傳功能。
const uploadSection = document.querySelector('.upload-section');
uploadSection.addEventListener('dragover', (e) => {e.preventDefault();uploadSection.style.borderColor = '#4CAF50';
});uploadSection.addEventListener('dragleave', () => {uploadSection.style.borderColor = '#ccc';
});uploadSection.addEventListener('drop', (e) => {e.preventDefault();uploadSection.style.borderColor = '#ccc';if (e.dataTransfer.files.length) {fileInput.files = e.dataTransfer.files;handleFileSelect({ target: fileInput });}
});
圖片預覽與裁剪框初始化
在圖片加載完成后,繪制到 canvas 上,并根據圖片尺寸調整畫布大小。初始化一個固定比例的裁剪框,居中顯示在畫布上。
function initCropper() {// 顯示原始圖片和裁剪區域originalImage.style.display = 'none';cropperContainer.style.display = 'inline-block';// 設置canvas尺寸const maxWidth = 500;imageRatio = originalImage.naturalWidth / originalImage.naturalHeight;let canvasWidth, canvasHeight;if (originalImage.naturalWidth > maxWidth) {canvasWidth = maxWidth;canvasHeight = maxWidth / imageRatio;} else {canvasWidth = originalImage.naturalWidth;canvasHeight = originalImage.naturalHeight;}sourceCanvas.width = canvasWidth;sourceCanvas.height = canvasHeight;// 繪制圖片到canvasconst ctx = sourceCanvas.getContext('2d');ctx.drawImage(originalImage, 0, 0, canvasWidth, canvasHeight);// 初始化選擇框 (1:1比例)const boxSize = Math.min(canvasWidth, canvasHeight) * 0.6;selection = {x: Math.max(0, Math.min((canvasWidth - boxSize) / 2, canvasWidth - boxSize)), // 確保初始位置在畫布范圍內y: Math.max(0, Math.min((canvasHeight - boxSize) / 2, canvasHeight - boxSize)), // 確保初始位置在畫布范圍內width: boxSize,height: boxSize,startX: 0,startY: 0,startWidth: 0,startHeight: 0};updateSelectionBox();cropBtn.disabled = false;
}
裁剪框拖動與調整大小
通過監聽鼠標事件(mousedown、mousemove、mouseup)實現裁剪框的拖動和調整大小功能。確保裁剪框始終位于畫布范圍內,并保持指定的比例。
selectionBox.addEventListener('mousedown', startDrag);
document.addEventListener('mousemove', handleDrag);
document.addEventListener('mouseup', endDrag);
const resizeHandle = document.querySelector('.resize-handle');
resizeHandle.addEventListener('mousedown', (e) => {e.stopPropagation();startResize(e);
});
function startDrag(e) {if (e.target.classList.contains('resize-handle')) {return; // 忽略調整大小手柄的點擊}isDragging = true;startX = e.clientX;startY = e.clientY;// 存儲初始位置selection.startX = selection.x;selection.startY = selection.y;e.preventDefault();
}
function startResize(e) {isResizing = true;startX = e.clientX;startY = e.clientY;// 存儲初始尺寸和位置selection.startX = selection.x;selection.startY = selection.y;selection.startWidth = selection.width;selection.startHeight = selection.height;e.preventDefault();
}
function handleDrag(e) {if (!isDragging && !isResizing) return;const dx = e.clientX - startX;const dy = e.clientY - startY;if (isDragging) {// 處理移動選擇框let newX = selection.startX + dx;let newY = selection.startY + dy;// 限制在canvas范圍內newX = Math.max(0, Math.min(newX, sourceCanvas.width - selection.width));newY = Math.max(0, Math.min(newY, sourceCanvas.height - selection.height));selection.x = newX;selection.y = newY;} else if (isResizing) {// 處理調整大小 (保持1:1比例)let newSize = Math.max(10, Math.min(selection.startWidth + (dx + dy) / 2, // 取dx和dy的平均值使調整更平滑Math.min(sourceCanvas.width - selection.startX,sourceCanvas.height - selection.startY)));// 應用新尺寸 (保持正方形)selection.width = newSize;selection.height = newSize;// 確保裁剪框不會超出畫布范圍if (selection.x + selection.width > sourceCanvas.width) {selection.x = sourceCanvas.width - selection.width;}if (selection.y + selection.height > sourceCanvas.height) {selection.y = sourceCanvas.height - selection.height;}}updateSelectionBox();
}
function endDrag() {isDragging = false;isResizing = false;
}
圖片裁剪與結果展示
使用 drawImage 方法從源畫布中裁剪出指定區域,并將其繪制到目標畫布上。
function cropImage() {const ctx = croppedCanvas.getContext('2d');// 設置裁剪后canvas的尺寸 (1:1)croppedCanvas.width = selection.width;croppedCanvas.height = selection.height;// 執行裁剪ctx.drawImage(sourceCanvas,selection.x, selection.y, selection.width, selection.height, // 源圖像裁剪區域0, 0, selection.width, selection.height // 目標canvas繪制區域);// 顯示裁剪結果croppedCanvas.style.display = 'block';noCropMessage.style.display = 'none';uploadBtn.disabled = false;downloadBtn.disabled = false;
}
圖片上傳與下載
提供模擬的上傳功能,使用 toBlob 方法獲取裁剪后的圖片數據。支持將裁剪后的圖片下載為 JPEG 格式的文件。
function uploadImage() {// 在實際應用中,這里應該將圖片數據發送到服務器croppedCanvas.toBlob((blob) => {// 創建FormData對象并添加圖片const formData = new FormData();formData.append('croppedImage', blob, 'cropped-image.jpg');// 模擬上傳延遲setTimeout(() => {alert('圖片上傳成功!(模擬)');console.log('上傳的圖片數據:', blob);// 在實際應用中,你可能需要處理服務器響應}, 1000);}, 'image/jpeg', 0.9);
}
function downloadImage() {if (!croppedCanvas.width || !croppedCanvas.height) {alert('請先裁剪圖片');return;}// 創建一個臨時的a標簽用于觸發下載const link = document.createElement('a');link.href = croppedCanvas.toDataURL('image/jpeg', 0.9);link.download = 'cropped-image.jpg'; // 設置下載文件名link.click();
}
擴展建議
- 支持多種裁剪比例:可以擴展代碼以支持不同的裁剪比例(如 4:3、16:9),并通過 UI 控件讓用戶選擇。
- 圖像縮放功能:添加對圖片縮放的支持,允許用戶放大或縮小圖片以便更精確地選擇裁剪區域。
- 服務器端集成:實際應用中,應將裁剪后的圖片發送到服務器進行存儲和處理,可以通過請求實現。
完整代碼
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>圖片裁剪上傳</title><style>body {max-width: 1200px;margin: 0 auto;padding: 20px;}.container {display: flex;flex-direction: column;gap: 20px;}h1 {text-align: center;}.upload-section {padding: 20px;text-align: center;border-radius: 5px;background: #f8f9fa;border: 2px dashed #dee2e6;transition: all 0.3s ease;cursor: pointer;}.upload-section:hover {border-color: #4CAF50;background: rgba(76, 175, 80, 0.05);}.file-label {background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);color: white;border-radius: 25px;padding: 12px 24px;transition: transform 0.2s;}.file-label:hover {transform: translateY(-2px);box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);}.preview-section {display: flex;flex-direction: column;gap: 20px;background: #ffffff;border-radius: 12px;padding: 20px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);}canvas {max-width: 100%;border: 1px solid #eee;display: block;}.cropper-container {position: relative;display: inline-block;}.selection-box {position: absolute;border: 2px dashed #000;background: rgba(255, 255, 255, 0.3);cursor: move;box-sizing: border-box;}.resize-handle {position: absolute;width: 10px;height: 10px;background: #fff;border: 2px solid #000;border-radius: 50%;bottom: -5px;right: -5px;cursor: se-resize;}button {padding: 10px 15px;background-color: #4CAF50;color: white;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;}button:hover {background-color: #45a049;}button {background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);border-radius: 25px;padding: 12px 24px;font-weight: 500;box-shadow: 0 4px 6px rgba(76, 175, 80, 0.1);transition: all 0.3s ease;}button:hover {transform: translateY(-2px);box-shadow: 0 6px 12px rgba(76, 175, 80, 0.2);}button:disabled {opacity: 0.6;cursor: not-allowed;}input[type="file"] {display: none;}.file-label {display: inline-block;padding: 10px 15px;background-color: #f0f0f0;border-radius: 4px;cursor: pointer;margin-bottom: 10px;}.controls {display: flex;gap: 10px;margin-top: 10px;justify-content: center;}.instruction {font-size: 14px;color: #666;margin-top: 10px;}.image-container {display: flex;gap: 20px;}.image-container > div {width: 500px;}</style>
</head>
<body>
<div class="container"><h1>圖片裁剪上傳</h1><div class="upload-section"><input type="file" id="fileInput" accept="image/*"><label for="fileInput" class="file-label">選擇圖片</label><p>或拖放圖片到此處</p></div><div class="preview-section"><div class="image-container"><div><h3>原始圖片</h3><img id="originalImage" style="max-width: 100%; display: none;"><div class="cropper-container" id="cropperContainer" style="display: none;"><canvas id="sourceCanvas"></canvas><div class="selection-box" id="selectionBox"><div class="resize-handle"></div></div></div><p class="instruction">拖動選擇框可移動位置,拖動右下角可調整大小</p></div><div><h3>裁剪結果</h3><canvas id="croppedCanvas" style="display: none;"></canvas><p id="noCropMessage">請先選擇圖片并設置裁剪區域</p></div></div></div><div class="controls"><button id="cropBtn" disabled>裁剪圖片</button><button id="uploadBtn" disabled>上傳圖片</button><button id="downloadBtn" disabled>下載圖片</button><button id="resetBtn">重置</button></div>
</div><script>// 獲取DOM元素const fileInput = document.getElementById('fileInput');const originalImage = document.getElementById('originalImage');const sourceCanvas = document.getElementById('sourceCanvas');const croppedCanvas = document.getElementById('croppedCanvas');const cropperContainer = document.getElementById('cropperContainer');const selectionBox = document.getElementById('selectionBox');const cropBtn = document.getElementById('cropBtn');const uploadBtn = document.getElementById('uploadBtn');const resetBtn = document.getElementById('resetBtn');const noCropMessage = document.getElementById('noCropMessage');const downloadBtn = document.getElementById('downloadBtn');// 全局變量let isDragging = false;let isResizing = false;let startX, startY;let selection = {x: 0,y: 0,width: 0,height: 0,startX: 0,startY: 0,startWidth: 0,startHeight: 0};let imageRatio = 1;// 監聽文件選擇fileInput.addEventListener('change', handleFileSelect);// 拖放功能const uploadSection = document.querySelector('.upload-section');uploadSection.addEventListener('dragover', (e) => {e.preventDefault();uploadSection.style.borderColor = '#4CAF50';});uploadSection.addEventListener('dragleave', () => {uploadSection.style.borderColor = '#ccc';});uploadSection.addEventListener('drop', (e) => {e.preventDefault();uploadSection.style.borderColor = '#ccc';if (e.dataTransfer.files.length) {fileInput.files = e.dataTransfer.files;handleFileSelect({ target: fileInput });}});// 選擇框鼠標事件selectionBox.addEventListener('mousedown', startDrag);document.addEventListener('mousemove', handleDrag);document.addEventListener('mouseup', endDrag);// 調整大小手柄事件const resizeHandle = document.querySelector('.resize-handle');resizeHandle.addEventListener('mousedown', (e) => {e.stopPropagation();startResize(e);});// 下載圖片function downloadImage() {if (!croppedCanvas.width || !croppedCanvas.height) {alert('請先裁剪圖片');return;}// 創建一個臨時的a標簽用于觸發下載const link = document.createElement('a');link.href = croppedCanvas.toDataURL('image/jpeg', 0.9);link.download = 'cropped-image.jpg'; // 設置下載文件名link.click();}// 按鈕事件cropBtn.addEventListener('click', cropImage);uploadBtn.addEventListener('click', uploadImage);resetBtn.addEventListener('click', resetAll);downloadBtn.addEventListener('click', downloadImage);// 處理文件選擇function handleFileSelect(event) {const file = event.target.files[0];if (!file || !file.type.match('image.*')) {alert('請選擇有效的圖片文件');return;}const reader = new FileReader();reader.onload = function(e) {originalImage.src = e.target.result;originalImage.onload = function() {initCropper();};};reader.readAsDataURL(file);}// 初始化裁剪器function initCropper() {// 顯示原始圖片和裁剪區域originalImage.style.display = 'none';cropperContainer.style.display = 'inline-block';// 設置canvas尺寸const maxWidth = 500;imageRatio = originalImage.naturalWidth / originalImage.naturalHeight;let canvasWidth, canvasHeight;if (originalImage.naturalWidth > maxWidth) {canvasWidth = maxWidth;canvasHeight = maxWidth / imageRatio;} else {canvasWidth = originalImage.naturalWidth;canvasHeight = originalImage.naturalHeight;}sourceCanvas.width = canvasWidth;sourceCanvas.height = canvasHeight;// 繪制圖片到canvasconst ctx = sourceCanvas.getContext('2d');ctx.drawImage(originalImage, 0, 0, canvasWidth, canvasHeight);// 初始化選擇框 (1:1比例)const boxSize = Math.min(canvasWidth, canvasHeight) * 0.6;selection = {x: Math.max(0, Math.min((canvasWidth - boxSize) / 2, canvasWidth - boxSize)), // 確保初始位置在畫布范圍內y: Math.max(0, Math.min((canvasHeight - boxSize) / 2, canvasHeight - boxSize)), // 確保初始位置在畫布范圍內width: boxSize,height: boxSize,startX: 0,startY: 0,startWidth: 0,startHeight: 0};updateSelectionBox();cropBtn.disabled = false;}// 更新選擇框位置和尺寸function updateSelectionBox() {selectionBox.style.left = `${selection.x}px`;selectionBox.style.top = `${selection.y}px`;selectionBox.style.width = `${selection.width}px`;selectionBox.style.height = `${selection.height}px`;}// 開始拖動function startDrag(e) {if (e.target.classList.contains('resize-handle')) {return; // 忽略調整大小手柄的點擊}isDragging = true;startX = e.clientX;startY = e.clientY;// 存儲初始位置selection.startX = selection.x;selection.startY = selection.y;e.preventDefault();}// 處理拖動function handleDrag(e) {if (!isDragging && !isResizing) return;const dx = e.clientX - startX;const dy = e.clientY - startY;if (isDragging) {// 處理移動選擇框let newX = selection.startX + dx;let newY = selection.startY + dy;// 限制在canvas范圍內newX = Math.max(0, Math.min(newX, sourceCanvas.width - selection.width));newY = Math.max(0, Math.min(newY, sourceCanvas.height - selection.height));selection.x = newX;selection.y = newY;} else if (isResizing) {// 處理調整大小 (保持1:1比例)let newSize = Math.max(10, Math.min(selection.startWidth + (dx + dy) / 2, // 取dx和dy的平均值使調整更平滑Math.min(sourceCanvas.width - selection.startX,sourceCanvas.height - selection.startY)));// 應用新尺寸 (保持正方形)selection.width = newSize;selection.height = newSize;// 確保裁剪框不會超出畫布范圍if (selection.x + selection.width > sourceCanvas.width) {selection.x = sourceCanvas.width - selection.width;}if (selection.y + selection.height > sourceCanvas.height) {selection.y = sourceCanvas.height - selection.height;}}updateSelectionBox();}// 結束拖動或調整大小function endDrag() {isDragging = false;isResizing = false;}// 開始調整大小function startResize(e) {isResizing = true;startX = e.clientX;startY = e.clientY;// 存儲初始尺寸和位置selection.startX = selection.x;selection.startY = selection.y;selection.startWidth = selection.width;selection.startHeight = selection.height;e.preventDefault();}// 裁剪圖片function cropImage() {const ctx = croppedCanvas.getContext('2d');// 設置裁剪后canvas的尺寸 (1:1)croppedCanvas.width = selection.width;croppedCanvas.height = selection.height;// 執行裁剪ctx.drawImage(sourceCanvas,selection.x, selection.y, selection.width, selection.height, // 源圖像裁剪區域0, 0, selection.width, selection.height // 目標canvas繪制區域);// 顯示裁剪結果croppedCanvas.style.display = 'block';noCropMessage.style.display = 'none';uploadBtn.disabled = false;downloadBtn.disabled = false;}// 上傳圖片function uploadImage() {// 在實際應用中,這里應該將圖片數據發送到服務器croppedCanvas.toBlob((blob) => {// 創建FormData對象并添加圖片const formData = new FormData();formData.append('croppedImage', blob, 'cropped-image.jpg');// 模擬上傳延遲setTimeout(() => {alert('圖片上傳成功!(模擬)');console.log('上傳的圖片數據:', blob);// 在實際應用中,你可能需要處理服務器響應}, 1000);}, 'image/jpeg', 0.9);}// 重置所有function resetAll() {// 隱藏元素cropperContainer.style.display = 'none';croppedCanvas.style.display = 'none';noCropMessage.style.display = 'block';originalImage.style.display = 'none';// 重置按鈕狀態cropBtn.disabled = true;uploadBtn.disabled = true;downloadBtn.disabled = true;// 清除文件輸入fileInput.value = '';// 清除畫布const ctx = sourceCanvas.getContext('2d');ctx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);const croppedCtx = croppedCanvas.getContext('2d');croppedCtx.clearRect(0, 0, croppedCanvas.width, croppedCanvas.height);}
</script>
</body>
</html>