-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
540 lines (458 loc) · 14.3 KB
/
app.js
File metadata and controls
540 lines (458 loc) · 14.3 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import * as pdfjsLib from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
// Configure PDF.js worker (use local worker file)
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
// DOM elements
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const docInput = document.getElementById('doc-input');
const stampInput = document.getElementById('stamp-input');
const downloadBtn = document.getElementById('download-btn');
const replaceDocBtn = document.getElementById('replace-doc-btn');
const resetStampBtn = document.getElementById('reset-stamp-btn');
const opacitySlider = document.getElementById('opacity-slider');
const opacityValue = document.getElementById('opacity-value');
const rotationSlider = document.getElementById('rotation-slider');
const rotationValue = document.getElementById('rotation-value');
// PDF page controls
const pdfPageControls = document.getElementById('pdf-page-controls');
const prevPageBtn = document.getElementById('prev-page-btn');
const nextPageBtn = document.getElementById('next-page-btn');
const pageInfo = document.getElementById('page-info');
// State
let docImg = null;
let stampImg = null;
let pdfDoc = null;
let currentPage = 1;
let totalPages = 1;
// Calculate default position (60% right, 60% down from document)
function getDefaultStampPosition() {
if (!docImg) {
return { x: 100, y: 100 };
}
return {
x: docImg.width * 0.6,
y: docImg.height * 0.6
};
}
// Stamp properties (persisted in localStorage)
const loadStampState = () => {
const savedX = localStorage.getItem('stampX');
const savedY = localStorage.getItem('stampY');
// If no saved position, use default based on document size
const defaultPos = getDefaultStampPosition();
return {
x: savedX !== null ? parseFloat(savedX) : defaultPos.x,
y: savedY !== null ? parseFloat(savedY) : defaultPos.y,
scale: parseFloat(localStorage.getItem('stampScale')) || 1.0,
rotation: parseFloat(localStorage.getItem('stampRotation')) || 0,
opacity: parseFloat(localStorage.getItem('stampOpacity')) || 1.0
};
};
let stamp = loadStampState();
// Interaction state
let isDragging = false;
let isResizing = false;
let dragOffset = { x: 0, y: 0 };
let resizeStartPos = { x: 0, y: 0 };
let resizeStartScale = 1.0;
// Save stamp state to localStorage
function saveStampState() {
localStorage.setItem('stampX', stamp.x);
localStorage.setItem('stampY', stamp.y);
localStorage.setItem('stampScale', stamp.scale);
localStorage.setItem('stampRotation', stamp.rotation);
localStorage.setItem('stampOpacity', stamp.opacity);
}
// Draw everything
function draw() {
if (!docImg) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
return;
}
// Set canvas size to match document
canvas.width = docImg.width;
canvas.height = docImg.height;
// Clear and draw document
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(docImg, 0, 0);
// Draw stamp if loaded
if (stampImg) {
const w = stampImg.width * stamp.scale;
const h = stampImg.height * stamp.scale;
const cx = stamp.x + w / 2;
const cy = stamp.y + h / 2;
ctx.save();
// Set opacity
ctx.globalAlpha = stamp.opacity;
// Translate to center, rotate, translate back
ctx.translate(cx, cy);
ctx.rotate((stamp.rotation * Math.PI) / 180);
ctx.translate(-cx, -cy);
// Draw stamp
ctx.drawImage(stampImg, stamp.x, stamp.y, w, h);
ctx.restore();
// Draw bounding box and handles (always at full opacity)
ctx.save();
ctx.globalAlpha = 1.0;
// Transform for bounding box
ctx.translate(cx, cy);
ctx.rotate((stamp.rotation * Math.PI) / 180);
ctx.translate(-cx, -cy);
// Bounding box
ctx.strokeStyle = 'rgba(102, 126, 234, 0.8)';
ctx.lineWidth = 2;
ctx.strokeRect(stamp.x, stamp.y, w, h);
// Resize handle (bottom-right corner)
ctx.fillStyle = '#fff';
ctx.strokeStyle = '#667eea';
ctx.lineWidth = 2;
const handleSize = 12;
ctx.fillRect(stamp.x + w - handleSize / 2, stamp.y + h - handleSize / 2, handleSize, handleSize);
ctx.strokeRect(stamp.x + w - handleSize / 2, stamp.y + h - handleSize / 2, handleSize, handleSize);
// Rotation handle (top-center)
ctx.beginPath();
ctx.arc(stamp.x + w / 2, stamp.y - 20, 6, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// Line from top to rotation handle
ctx.strokeStyle = 'rgba(102, 126, 234, 0.5)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(stamp.x + w / 2, stamp.y);
ctx.lineTo(stamp.x + w / 2, stamp.y - 20);
ctx.stroke();
ctx.restore();
}
}
// Get rotated point (inverse transform for hit detection)
function getRotatedPoint(px, py, cx, cy, angle) {
const rad = (-angle * Math.PI) / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const dx = px - cx;
const dy = py - cy;
return {
x: dx * cos - dy * sin + cx,
y: dx * sin + dy * cos + cy
};
}
// Check if point is inside rotated stamp
function isInsideStamp(mx, my) {
if (!stampImg) return false;
const w = stampImg.width * stamp.scale;
const h = stampImg.height * stamp.scale;
const cx = stamp.x + w / 2;
const cy = stamp.y + h / 2;
const rotated = getRotatedPoint(mx, my, cx, cy, stamp.rotation);
return rotated.x >= stamp.x && rotated.x <= stamp.x + w &&
rotated.y >= stamp.y && rotated.y <= stamp.y + h;
}
// Check if point is on resize handle
function isOnResizeHandle(mx, my) {
if (!stampImg) return false;
const w = stampImg.width * stamp.scale;
const h = stampImg.height * stamp.scale;
const cx = stamp.x + w / 2;
const cy = stamp.y + h / 2;
const rotated = getRotatedPoint(mx, my, cx, cy, stamp.rotation);
const handleSize = 12;
return rotated.x >= stamp.x + w - handleSize &&
rotated.x <= stamp.x + w + handleSize &&
rotated.y >= stamp.y + h - handleSize &&
rotated.y <= stamp.y + h + handleSize;
}
// Render PDF page to image
async function renderPDFPage(pdf, pageNum) {
const page = await pdf.getPage(pageNum);
const viewport = page.getViewport({ scale: 2.0 }); // 2x scale for better quality
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = viewport.width;
tempCanvas.height = viewport.height;
await page.render({
canvasContext: tempCtx,
viewport: viewport
}).promise;
// Convert canvas to image
return new Promise((resolve) => {
const img = new Image();
img.onload = () => resolve(img);
img.src = tempCanvas.toDataURL();
});
}
// Load document (image or PDF)
docInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
// Reset PDF state
pdfDoc = null;
currentPage = 1;
totalPages = 1;
pdfPageControls.style.display = 'none';
if (file.type === 'application/pdf') {
try {
const arrayBuffer = await file.arrayBuffer();
pdfDoc = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
totalPages = pdfDoc.numPages;
currentPage = 1;
// Show page controls
pdfPageControls.style.display = 'block';
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
// Render first page
docImg = await renderPDFPage(pdfDoc, currentPage);
// Reset stamp position to default for new document
const defaultPos = getDefaultStampPosition();
stamp.x = defaultPos.x;
stamp.y = defaultPos.y;
draw();
} catch (error) {
console.error('Error loading PDF:', error);
alert('Error loading PDF. Please try a different file.');
}
} else {
// Load as image
const img = new Image();
img.onload = () => {
docImg = img;
// Reset stamp position to default for new document
const defaultPos = getDefaultStampPosition();
stamp.x = defaultPos.x;
stamp.y = defaultPos.y;
draw();
};
img.src = URL.createObjectURL(file);
}
});
// Load stamp
stampInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const img = new Image();
img.onload = () => {
stampImg = img;
draw();
};
img.src = URL.createObjectURL(file);
});
// Mouse events for dragging and resizing
canvas.addEventListener('mousedown', (e) => {
if (!stampImg) return;
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const mx = (e.clientX - rect.left) * scaleX;
const my = (e.clientY - rect.top) * scaleY;
// Check resize handle first
if (isOnResizeHandle(mx, my)) {
isResizing = true;
resizeStartPos = { x: mx, y: my };
resizeStartScale = stamp.scale;
canvas.style.cursor = 'nwse-resize';
return;
}
// Check if inside stamp
if (isInsideStamp(mx, my)) {
isDragging = true;
dragOffset.x = mx - stamp.x;
dragOffset.y = my - stamp.y;
canvas.style.cursor = 'grabbing';
}
});
canvas.addEventListener('mousemove', (e) => {
if (!stampImg) return;
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const mx = (e.clientX - rect.left) * scaleX;
const my = (e.clientY - rect.top) * scaleY;
if (isDragging) {
stamp.x = mx - dragOffset.x;
stamp.y = my - dragOffset.y;
draw();
} else if (isResizing) {
const dx = mx - resizeStartPos.x;
const dy = my - resizeStartPos.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const scaleDelta = dist / 100;
stamp.scale = Math.max(0.1, resizeStartScale + (dx > 0 ? scaleDelta : -scaleDelta));
draw();
} else {
// Update cursor based on position
if (isOnResizeHandle(mx, my)) {
canvas.style.cursor = 'nwse-resize';
} else if (isInsideStamp(mx, my)) {
canvas.style.cursor = 'grab';
} else {
canvas.style.cursor = 'default';
}
}
});
canvas.addEventListener('mouseup', () => {
if (isDragging || isResizing) {
saveStampState();
}
isDragging = false;
isResizing = false;
canvas.style.cursor = 'default';
});
canvas.addEventListener('mouseleave', () => {
if (isDragging || isResizing) {
saveStampState();
}
isDragging = false;
isResizing = false;
});
// Opacity slider
opacitySlider.addEventListener('input', (e) => {
stamp.opacity = parseFloat(e.target.value) / 100;
opacityValue.textContent = e.target.value + '%';
saveStampState();
draw();
});
// Rotation slider
rotationSlider.addEventListener('input', (e) => {
stamp.rotation = parseFloat(e.target.value);
rotationValue.textContent = e.target.value + '°';
saveStampState();
draw();
});
// Set initial slider values from saved state
opacitySlider.value = stamp.opacity * 100;
opacityValue.textContent = Math.round(stamp.opacity * 100) + '%';
rotationSlider.value = stamp.rotation;
rotationValue.textContent = stamp.rotation + '°';
// Download button
downloadBtn.addEventListener('click', () => {
if (!docImg) {
alert('Please upload a document first!');
return;
}
// Create a temporary canvas for final output (no bounding box)
const outputCanvas = document.createElement('canvas');
outputCanvas.width = canvas.width;
outputCanvas.height = canvas.height;
const outputCtx = outputCanvas.getContext('2d');
// Draw document
outputCtx.drawImage(docImg, 0, 0);
// Draw stamp without bounding box
if (stampImg) {
const w = stampImg.width * stamp.scale;
const h = stampImg.height * stamp.scale;
const cx = stamp.x + w / 2;
const cy = stamp.y + h / 2;
outputCtx.save();
outputCtx.globalAlpha = stamp.opacity;
outputCtx.translate(cx, cy);
outputCtx.rotate((stamp.rotation * Math.PI) / 180);
outputCtx.translate(-cx, -cy);
outputCtx.drawImage(stampImg, stamp.x, stamp.y, w, h);
outputCtx.restore();
}
const link = document.createElement('a');
const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-').replace('T', '_');
link.download = `stamped-document-${timestamp}.png`;
link.href = outputCanvas.toDataURL('image/png');
link.click();
});
// PDF page navigation
prevPageBtn.addEventListener('click', async () => {
if (!pdfDoc || currentPage <= 1) return;
currentPage--;
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
docImg = await renderPDFPage(pdfDoc, currentPage);
draw();
});
nextPageBtn.addEventListener('click', async () => {
if (!pdfDoc || currentPage >= totalPages) return;
currentPage++;
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
docImg = await renderPDFPage(pdfDoc, currentPage);
draw();
});
// Replace document button
replaceDocBtn.addEventListener('click', () => {
docInput.value = '';
docImg = null;
pdfDoc = null;
pdfPageControls.style.display = 'none';
draw();
});
// Reset stamp position button
resetStampBtn.addEventListener('click', () => {
const defaultPos = getDefaultStampPosition();
stamp.x = defaultPos.x;
stamp.y = defaultPos.y;
stamp.scale = 1.0;
stamp.rotation = 0;
stamp.opacity = 1.0;
opacitySlider.value = 100;
opacityValue.textContent = '100%';
rotationSlider.value = 0;
rotationValue.textContent = '0°';
saveStampState();
draw();
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (!stampImg) return;
const step = e.shiftKey ? 10 : 1;
switch (e.key) {
case 'ArrowLeft':
e.preventDefault();
stamp.x -= step;
draw();
saveStampState();
break;
case 'ArrowRight':
e.preventDefault();
stamp.x += step;
draw();
saveStampState();
break;
case 'ArrowUp':
e.preventDefault();
stamp.y -= step;
draw();
saveStampState();
break;
case 'ArrowDown':
e.preventDefault();
stamp.y += step;
draw();
saveStampState();
break;
case '+':
case '=':
e.preventDefault();
stamp.scale = Math.min(5, stamp.scale + 0.1);
draw();
saveStampState();
break;
case '-':
case '_':
e.preventDefault();
stamp.scale = Math.max(0.1, stamp.scale - 0.1);
draw();
saveStampState();
break;
case 'r':
case 'R':
e.preventDefault();
resetStampBtn.click();
break;
case 'd':
case 'D':
e.preventDefault();
downloadBtn.click();
break;
}
});
// Register service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
console.log('PWA ready for offline use');
});
}
// Initial draw
draw();