-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
273 lines (231 loc) · 9.93 KB
/
Copy pathscript.js
File metadata and controls
273 lines (231 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// --- script.js ---
const imageInput = document.getElementById('imageInput');
const sourceImage = document.getElementById('sourceImage');
const cropBox = document.getElementById('cropBox');
const cropBtn = document.getElementById('cropBtn');
const croppedResult = document.getElementById('croppedResult');
const workspace = document.getElementById('workspace');
const downloadArea = document.getElementById('downloadArea');
const downloadLink = document.getElementById('downloadLink');
const shapeSelector = document.getElementById('shapeSelector');
const shapeRadios = document.querySelectorAll('input[name="cropShape"]');
// Interaction State Variables
let isDragging = false;
let isResizing = false;
let currentShape = 'circle';
let dragOffsetX = 0;
let dragOffsetY = 0;
// Resize State Variables
let resizeDir = '';
let startX, startY, startW, startH, startL, startT;
// 1. Handle Image Upload
imageInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
sourceImage.onload = function() {
sourceImage.classList.add('loaded');
// Initialize default crop box size and center it perfectly
const boxSize = 200;
cropBox.style.width = boxSize + 'px';
cropBox.style.height = boxSize + 'px';
cropBox.style.left = (sourceImage.clientWidth - boxSize) / 2 + 'px';
cropBox.style.top = (sourceImage.clientHeight - boxSize) / 2 + 'px';
shapeSelector.classList.remove('hidden');
downloadArea.classList.add('hidden');
croppedResult.classList.remove('has-result');
updateShapeMode();
};
sourceImage.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
// 2. Handle Shape Switching
shapeRadios.forEach(radio => {
radio.addEventListener('change', function(e) {
currentShape = e.target.value;
updateShapeMode();
});
});
function updateShapeMode() {
if (currentShape === 'circle') {
cropBox.classList.remove('rect-shape');
// Re-enforce perfect square bounds when switching back to circle
const minDim = Math.min(cropBox.offsetWidth, cropBox.offsetHeight);
cropBox.style.width = minDim + 'px';
cropBox.style.height = minDim + 'px';
} else {
cropBox.classList.add('rect-shape');
}
}
// 3. Drag Logic (Smooth offset dragging)
function startDrag(e) {
if (e.target.classList.contains('resize-handle')) return; // Ignore if clicking a resize handle
// Check if clicked exactly on cropBox (or inside it)
if (e.target === cropBox || cropBox.contains(e.target)) {
isDragging = true;
cropBox.style.cursor = 'grabbing';
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const rect = cropBox.getBoundingClientRect();
// Calculate offset from cursor to top-left of the box
dragOffsetX = clientX - rect.left;
dragOffsetY = clientY - rect.top;
if(e.touches) e.preventDefault();
}
}
// 4. Resize Logic Initialization
document.querySelectorAll('.resize-handle').forEach(handle => {
handle.addEventListener('mousedown', initResize);
handle.addEventListener('touchstart', initResize, { passive: false });
});
function initResize(e) {
e.preventDefault();
e.stopPropagation();
isResizing = true;
resizeDir = e.target.dataset.dir;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
startX = clientX;
startY = clientY;
startW = cropBox.offsetWidth;
startH = cropBox.offsetHeight;
startL = cropBox.offsetLeft;
startT = cropBox.offsetTop;
}
// Global Move Handlers for Drag & Resize
window.addEventListener('mousemove', handleMove);
window.addEventListener('touchmove', handleMove, { passive: false });
window.addEventListener('mouseup', stopAll);
window.addEventListener('touchend', stopAll);
workspace.addEventListener('mousedown', startDrag);
workspace.addEventListener('touchstart', startDrag, { passive: false });
function handleMove(e) {
if (!isDragging && !isResizing) return;
e.preventDefault();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const workRect = workspace.getBoundingClientRect();
// Boundary Limits (Relative to the source image dimensions)
const minX = 0;
const minY = 0;
const maxX = sourceImage.clientWidth;
const maxY = sourceImage.clientHeight;
if (isDragging) {
// Calculate new X/Y using relative workspace position and mouse offset
let newL = (clientX - workRect.left) - dragOffsetX;
let newT = (clientY - workRect.top) - dragOffsetY;
// Apply drag boundaries
newL = Math.max(minX, Math.min(newL, maxX - cropBox.offsetWidth));
newT = Math.max(minY, Math.min(newT, maxY - cropBox.offsetHeight));
cropBox.style.left = newL + 'px';
cropBox.style.top = newT + 'px';
} else if (isResizing) {
let dx = clientX - startX;
let dy = clientY - startY;
let newW = startW;
let newH = startH;
let newL = startL;
let newT = startT;
if (currentShape === 'circle') {
// Circle Mode: Calculate uniform sizing to keep aspect ratio 1:1
let sizeDelta = 0;
if (resizeDir === 'se') {
sizeDelta = Math.max(dx, dy);
newW = startW + sizeDelta; newH = startH + sizeDelta;
} else if (resizeDir === 'nw') {
sizeDelta = Math.max(-dx, -dy);
newW = startW + sizeDelta; newH = startH + sizeDelta;
newL = startL - sizeDelta; newT = startT - sizeDelta;
} else if (resizeDir === 'ne') {
sizeDelta = Math.max(dx, -dy);
newW = startW + sizeDelta; newH = startH + sizeDelta;
newT = startT - sizeDelta;
} else if (resizeDir === 'sw') {
sizeDelta = Math.max(-dx, dy);
newW = startW + sizeDelta; newH = startH + sizeDelta;
newL = startL - sizeDelta;
}
} else {
// Rectangle Mode: Freeform 8-axis resizing
if (resizeDir.includes('e')) newW = startW + dx;
if (resizeDir.includes('w')) { newW = startW - dx; newL = startL + dx; }
if (resizeDir.includes('s')) newH = startH + dy;
if (resizeDir.includes('n')) { newH = startH - dy; newT = startT + dy; }
}
// --- Restrict Minimum Size ---
const MIN_SIZE = 50;
if (newW < MIN_SIZE) {
if (resizeDir.includes('w')) newL = startL + (startW - MIN_SIZE);
newW = MIN_SIZE;
}
if (newH < MIN_SIZE) {
if (resizeDir.includes('n')) newT = startT + (startH - MIN_SIZE);
newH = MIN_SIZE;
}
// --- Boundary Edge Restrictions ---
if (newL < minX) { newW = newW - (minX - newL); newL = minX; }
if (newT < minY) { newH = newH - (minY - newT); newT = minY; }
if (newL + newW > maxX) newW = maxX - newL;
if (newT + newH > maxY) newH = maxY - newT;
// Strict Aspect Ratio Re-Enforcement for Circle (if it hit a wall)
if (currentShape === 'circle') {
const strictSize = Math.min(newW, newH);
if (resizeDir.includes('w')) newL = newL + (newW - strictSize);
if (resizeDir.includes('n')) newT = newT + (newH - strictSize);
newW = strictSize;
newH = strictSize;
}
// Apply Styles
cropBox.style.width = newW + 'px';
cropBox.style.height = newH + 'px';
cropBox.style.left = newL + 'px';
cropBox.style.top = newT + 'px';
}
}
function stopAll() {
isDragging = false;
isResizing = false;
cropBox.style.cursor = 'move';
}
// 5. Final Crop Logic (Untouched but naturally relies on our flawless bounds)
cropBtn.addEventListener('click', function() {
if (!sourceImage.src || !sourceImage.classList.contains('loaded')) {
return alert('Please upload an image first!');
}
// Native pixel vs Rendered pixel scaling
const scaleX = sourceImage.naturalWidth / sourceImage.clientWidth;
const scaleY = sourceImage.naturalHeight / sourceImage.clientHeight;
const boxRect = cropBox.getBoundingClientRect();
const imageRect = sourceImage.getBoundingClientRect();
const cropX = (boxRect.left - imageRect.left) * scaleX;
const cropY = (boxRect.top - imageRect.top) * scaleY;
const cropWidth = boxRect.width * scaleX;
const cropHeight = boxRect.height * scaleY;
const canvas = document.createElement('canvas');
canvas.width = cropWidth;
canvas.height = cropHeight;
const ctx = canvas.getContext('2d');
if (currentShape === 'circle') {
const radius = cropWidth / 2;
ctx.beginPath();
ctx.arc(radius, radius, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.clip();
}
ctx.drawImage(
sourceImage,
cropX, cropY,
cropWidth, cropHeight,
0, 0,
cropWidth, cropHeight
);
const croppedDataUrl = canvas.toDataURL('image/png');
croppedResult.src = croppedDataUrl;
croppedResult.classList.add('has-result');
downloadLink.href = croppedDataUrl;
downloadLink.download = `crop-result-${currentShape}.png`;
downloadArea.classList.remove('hidden');
});