Image_Cropper / index.html
Examups's picture
Update index.html
00645a2 verified
Raw History Blame Contribute Delete
23.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Cropper with Rounded Corners</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
.upload-section {
text-align: center;
margin-bottom: 20px;
padding: 20px;
border: 2px dashed #ccc;
border-radius: 5px;
}
.preview-container {
position: relative;
margin: 20px auto;
max-width: 100%;
overflow: hidden;
border: 1px solid #ddd;
}
#image-preview {
display: block;
max-width: 100%;
}
.crop-box {
position: absolute;
border: 2px dashed rgba(255, 255, 255, 0.8);
box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
cursor: move;
}
.controls {
margin-top: 20px;
display: flex;
flex-wrap: wrap;
gap: 15px;
justify-content: center;
}
.control-group {
display: flex;
flex-direction: column;
min-width: 200px;
}
label {
margin-bottom: 5px;
font-weight: bold;
}
input[type="range"], input[type="number"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
text-align: center;
}
#cropped-result {
max-width: 100%;
border: 1px solid #ddd;
margin-top: 10px;
}
.resize-handle {
position: absolute;
width: 10px;
height: 10px;
background-color: white;
border: 1px solid #333;
z-index: 10;
}
.resize-handle-nw {
top: -5px;
left: -5px;
cursor: nw-resize;
}
.resize-handle-ne {
top: -5px;
right: -5px;
cursor: ne-resize;
}
.resize-handle-sw {
bottom: -5px;
left: -5px;
cursor: sw-resize;
}
.resize-handle-se {
bottom: -5px;
right: -5px;
cursor: se-resize;
}
</style>
</head>
<body>
<div class="container">
<h1>Image Cropper with Rounded Corners</h1>
<div class="upload-section">
<input type="file" id="image-upload" accept="image/*">
<p>or drag and drop image here</p>
</div>
<div class="preview-container" id="preview-container" style="display: none;">
<img id="image-preview">
<div class="crop-box" id="crop-box">
<div class="resize-handle resize-handle-nw"></div>
<div class="resize-handle resize-handle-ne"></div>
<div class="resize-handle resize-handle-sw"></div>
<div class="resize-handle resize-handle-se"></div>
</div>
</div>
<div class="controls">
<div class="control-group">
<label for="edge-reduction">Edge Reduction (%)</label>
<input type="range" id="edge-reduction" min="0" max="50" value="0" step="1">
<input type="number" id="edge-reduction-value" min="0" max="50" value="0" step="1">
</div>
<div class="control-group">
<label for="corner-radius">Corner Radius (%)</label>
<input type="range" id="corner-radius" min="0" max="50" value="0" step="1">
<input type="number" id="corner-radius-value" min="0" max="50" value="0" step="1">
</div>
<div class="control-group">
<label for="aspect-ratio">Aspect Ratio</label>
<select id="aspect-ratio">
<option value="free">Free</option>
<option value="1">1:1 (Square)</option>
<option value="4/3">4:3</option>
<option value="16/9">16:9</option>
<option value="3/2">3:2</option>
<option value="custom">Custom</option>
</select>
</div>
<div class="control-group" id="custom-aspect-group" style="display: none;">
<label for="custom-aspect-width">Custom Ratio</label>
<div style="display: flex; gap: 5px;">
<input type="number" id="custom-aspect-width" min="1" value="1" style="width: 50px;">
<span>:</span>
<input type="number" id="custom-aspect-height" min="1" value="1" style="width: 50px;">
</div>
</div>
</div>
<div class="controls" style="justify-content: center; margin-top: 10px;">
<button id="crop-button">Crop Image</button>
<button id="download-button" disabled>Download Cropped Image</button>
</div>
<div class="result" id="result" style="display: none;">
<h3>Cropped Result</h3>
<img id="cropped-result">
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM elements
const imageUpload = document.getElementById('image-upload');
const previewContainer = document.getElementById('preview-container');
const imagePreview = document.getElementById('image-preview');
const cropBox = document.getElementById('crop-box');
const edgeReduction = document.getElementById('edge-reduction');
const edgeReductionValue = document.getElementById('edge-reduction-value');
const cornerRadius = document.getElementById('corner-radius');
const cornerRadiusValue = document.getElementById('corner-radius-value');
const aspectRatio = document.getElementById('aspect-ratio');
const customAspectGroup = document.getElementById('custom-aspect-group');
const customAspectWidth = document.getElementById('custom-aspect-width');
const customAspectHeight = document.getElementById('custom-aspect-height');
const cropButton = document.getElementById('crop-button');
const downloadButton = document.getElementById('download-button');
const result = document.getElementById('result');
const croppedResult = document.getElementById('cropped-result');
// Variables
let imageLoaded = false;
let currentImage = null;
let cropBoxX = 0;
let cropBoxY = 0;
let cropBoxWidth = 0;
let cropBoxHeight = 0;
let isDragging = false;
let isResizing = false;
let resizeHandle = null;
let startX, startY;
let startWidth, startHeight;
let startLeft, startTop;
let currentAspectRatio = null;
// Event listeners
imageUpload.addEventListener('change', handleImageUpload);
edgeReduction.addEventListener('input', updateEdgeReductionValue);
edgeReductionValue.addEventListener('input', updateEdgeReductionSlider);
cornerRadius.addEventListener('input', updateCornerRadiusValue);
cornerRadiusValue.addEventListener('input', updateCornerRadiusSlider);
aspectRatio.addEventListener('change', updateAspectRatio);
customAspectWidth.addEventListener('input', updateCustomAspectRatio);
customAspectHeight.addEventListener('input', updateCustomAspectRatio);
cropButton.addEventListener('click', cropImage);
downloadButton.addEventListener('click', downloadCroppedImage);
// Drag and drop
const uploadSection = document.querySelector('.upload-section');
uploadSection.addEventListener('dragover', (e) => {
e.preventDefault();
uploadSection.style.borderColor = '#4CAF50';
uploadSection.style.backgroundColor = '#f0fff0';
});
uploadSection.addEventListener('dragleave', () => {
uploadSection.style.borderColor = '#ccc';
uploadSection.style.backgroundColor = '';
});
uploadSection.addEventListener('drop', (e) => {
e.preventDefault();
uploadSection.style.borderColor = '#ccc';
uploadSection.style.backgroundColor = '';
if (e.dataTransfer.files.length) {
imageUpload.files = e.dataTransfer.files;
handleImageUpload();
}
});
// Crop box interaction
cropBox.addEventListener('mousedown', startDrag);
document.addEventListener('mousemove', handleDrag);
document.addEventListener('mouseup', stopDrag);
// Resize handles
const resizeHandles = document.querySelectorAll('.resize-handle');
resizeHandles.forEach(handle => {
handle.addEventListener('mousedown', startResize);
});
// Functions
function handleImageUpload() {
const file = imageUpload.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
imagePreview.src = e.target.result;
currentImage = new Image();
currentImage.onload = function() {
imageLoaded = true;
previewContainer.style.display = 'block';
initializeCropBox();
};
currentImage.src = e.target.result;
};
reader.readAsDataURL(file);
}
function initializeCropBox() {
const containerWidth = previewContainer.offsetWidth;
const containerHeight = previewContainer.offsetHeight;
// Set initial crop box size (80% of the smaller dimension)
const size = Math.min(containerWidth, containerHeight) * 0.8;
cropBoxWidth = size;
cropBoxHeight = size;
// Center the crop box
cropBoxX = (containerWidth - cropBoxWidth) / 2;
cropBoxY = (containerHeight - cropBoxHeight) / 2;
updateCropBox();
updateAspectRatio();
}
function updateCropBox() {
cropBox.style.width = `${cropBoxWidth}px`;
cropBox.style.height = `${cropBoxHeight}px`;
cropBox.style.left = `${cropBoxX}px`;
cropBox.style.top = `${cropBoxY}px`;
}
function startDrag(e) {
if (e.target.classList.contains('resize-handle')) return;
isDragging = true;
startX = e.clientX;
startY = e.clientY;
startLeft = cropBoxX;
startTop = cropBoxY;
e.preventDefault();
}
function handleDrag(e) {
if (isDragging) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
// Calculate new position with boundary checks
const newLeft = Math.max(0, Math.min(startLeft + dx, previewContainer.offsetWidth - cropBoxWidth));
const newTop = Math.max(0, Math.min(startTop + dy, previewContainer.offsetHeight - cropBoxHeight));
cropBoxX = newLeft;
cropBoxY = newTop;
updateCropBox();
} else if (isResizing) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
let newWidth = startWidth;
let newHeight = startHeight;
// Calculate new dimensions based on which handle is being used
if (resizeHandle.classList.contains('resize-handle-nw')) {
newWidth = Math.max(50, startWidth - dx);
newHeight = currentAspectRatio ? newWidth / currentAspectRatio : startHeight - dy;
if (currentAspectRatio) {
newHeight = newWidth / currentAspectRatio;
cropBoxX = startLeft + (startWidth - newWidth);
cropBoxY = startTop + (startHeight - newHeight);
} else {
newHeight = startHeight - dy;
cropBoxX = startLeft + (startWidth - newWidth);
cropBoxY = startTop + (startHeight - newHeight);
}
} else if (resizeHandle.classList.contains('resize-handle-ne')) {
newWidth = Math.max(50, startWidth + dx);
newHeight = currentAspectRatio ? newWidth / currentAspectRatio : startHeight - dy;
if (currentAspectRatio) {
cropBoxY = startTop + (startHeight - newHeight);
} else {
newHeight = startHeight - dy;
cropBoxY = startTop + (startHeight - newHeight);
}
} else if (resizeHandle.classList.contains('resize-handle-sw')) {
newWidth = Math.max(50, startWidth - dx);
newHeight = currentAspectRatio ? newWidth / currentAspectRatio : startHeight + dy;
if (currentAspectRatio) {
cropBoxX = startLeft + (startWidth - newWidth);
} else {
newHeight = startHeight + dy;
cropBoxX = startLeft + (startWidth - newWidth);
}
} else if (resizeHandle.classList.contains('resize-handle-se')) {
newWidth = Math.max(50, startWidth + dx);
newHeight = currentAspectRatio ? newWidth / currentAspectRatio : startHeight + dy;
}
// Boundary checks
if (cropBoxX + newWidth > previewContainer.offsetWidth) {
newWidth = previewContainer.offsetWidth - cropBoxX;
if (currentAspectRatio) {
newHeight = newWidth / currentAspectRatio;
}
}
if (cropBoxY + newHeight > previewContainer.offsetHeight) {
newHeight = previewContainer.offsetHeight - cropBoxY;
if (currentAspectRatio) {
newWidth = newHeight * currentAspectRatio;
}
}
cropBoxWidth = newWidth;
cropBoxHeight = newHeight;
updateCropBox();
}
}
function stopDrag() {
isDragging = false;
isResizing = false;
resizeHandle = null;
}
function startResize(e) {
isResizing = true;
resizeHandle = e.target;
startX = e.clientX;
startY = e.clientY;
startWidth = cropBoxWidth;
startHeight = cropBoxHeight;
startLeft = cropBoxX;
startTop = cropBoxY;
e.preventDefault();
e.stopPropagation();
}
function updateEdgeReductionValue() {
edgeReductionValue.value = edgeReduction.value;
}
function updateEdgeReductionSlider() {
const value = Math.min(50, Math.max(0, parseInt(edgeReductionValue.value) || 0));
edgeReductionValue.value = value;
edgeReduction.value = value;
}
function updateCornerRadiusValue() {
cornerRadiusValue.value = cornerRadius.value;
}
function updateCornerRadiusSlider() {
const value = Math.min(50, Math.max(0, parseInt(cornerRadiusValue.value) || 0));
cornerRadiusValue.value = value;
cornerRadius.value = value;
}
function updateAspectRatio() {
const ratio = aspectRatio.value;
if (ratio === 'custom') {
customAspectGroup.style.display = 'flex';
updateCustomAspectRatio();
} else {
customAspectGroup.style.display = 'none';
if (ratio === 'free') {
currentAspectRatio = null;
} else {
currentAspectRatio = eval(ratio); // Safe in this context as we control the options
applyAspectRatio();
}
}
}
function updateCustomAspectRatio() {
const width = parseInt(customAspectWidth.value) || 1;
const height = parseInt(customAspectHeight.value) || 1;
currentAspectRatio = width / height;
applyAspectRatio();
}
function applyAspectRatio() {
if (currentAspectRatio) {
// Adjust height based on current width to maintain aspect ratio
cropBoxHeight = cropBoxWidth / currentAspectRatio;
// Check if the new height exceeds container bounds
if (cropBoxY + cropBoxHeight > previewContainer.offsetHeight) {
cropBoxHeight = previewContainer.offsetHeight - cropBoxY;
cropBoxWidth = cropBoxHeight * currentAspectRatio;
}
updateCropBox();
}
}
function cropImage() {
if (!imageLoaded) return;
const reductionPercent = parseInt(edgeReduction.value) / 100;
const cornerRadiusPercent = parseInt(cornerRadius.value);
// Calculate the actual crop area on the original image
const scaleX = currentImage.width / imagePreview.offsetWidth;
const scaleY = currentImage.height / imagePreview.offsetHeight;
// Apply edge reduction
const reductionX = cropBoxWidth * reductionPercent;
const reductionY = cropBoxHeight * reductionPercent;
const cropX = cropBoxX * scaleX + reductionX * scaleX / 2;
const cropY = cropBoxY * scaleY + reductionY * scaleY / 2;
const cropWidth = cropBoxWidth * scaleX - reductionX * scaleX;
const cropHeight = cropBoxHeight * scaleY - reductionY * scaleY;
// Create a canvas to draw the cropped image
const canvas = document.createElement('canvas');
canvas.width = cropWidth;
canvas.height = cropHeight;
const ctx = canvas.getContext('2d');
// Draw the image first
ctx.drawImage(
currentImage,
cropX, cropY, cropWidth, cropHeight,
0, 0, cropWidth, cropHeight
);
// Apply rounded corners if radius is greater than 0
if (cornerRadiusPercent > 0) {
const radius = (Math.min(cropWidth, cropHeight) / 2) * (cornerRadiusPercent / 100);
// Create a clipping path with rounded corners
ctx.globalCompositeOperation = 'destination-in';
ctx.beginPath();
ctx.moveTo(radius, 0);
ctx.lineTo(cropWidth - radius, 0);
ctx.quadraticCurveTo(cropWidth, 0, cropWidth, radius);
ctx.lineTo(cropWidth, cropHeight - radius);
ctx.quadraticCurveTo(cropWidth, cropHeight, cropWidth - radius, cropHeight);
ctx.lineTo(radius, cropHeight);
ctx.quadraticCurveTo(0, cropHeight, 0, cropHeight - radius);
ctx.lineTo(0, radius);
ctx.quadraticCurveTo(0, 0, radius, 0);
ctx.closePath();
ctx.fill();
}
// Display the result
croppedResult.src = canvas.toDataURL('image/png');
result.style.display = 'block';
downloadButton.disabled = false;
// Scroll to result
result.scrollIntoView({ behavior: 'smooth' });
}
function downloadCroppedImage() {
if (!croppedResult.src) return;
const link = document.createElement('a');
link.download = 'cropped-image.png';
link.href = croppedResult.src;
link.click();
}
});
</script>
</body>
</html>