-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
401 lines (341 loc) · 14.1 KB
/
script.js
File metadata and controls
401 lines (341 loc) · 14.1 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
document.addEventListener('DOMContentLoaded', async () => {
let config = null;
const posterArea = document.getElementById('posterArea');
const canvas = document.getElementById('userImageCanvas');
const ctx = canvas.getContext('2d');
const imageInput = document.getElementById('imageInput');
const zoomSlider = document.getElementById('zoomSlider');
const controlsPanel = document.getElementById('controlsPanel');
const innerUploadPlaceholder = document.getElementById('innerUploadPlaceholder');
const downloadBtn = document.getElementById('downloadBtn');
const primaryUploadBtn = document.getElementById('primaryUploadBtn');
const frameImageEl = document.getElementById('frameImage');
const rotateSlider = document.getElementById('rotateSlider');
const zoomValDisplay = document.getElementById('zoomValDisplay');
const rotateValDisplay = document.getElementById('rotateValDisplay');
const brightSlider = document.getElementById('brightSlider');
const brightValDisplay = document.getElementById('brightValDisplay');
const flipBtn = document.getElementById('flipBtn');
const stickyMobileActions = document.getElementById('stickyMobileActions');
const mobileReupload = document.getElementById('mobileReupload');
const mobileDownload = document.getElementById('mobileDownload');
// State
const state = {
frameImg: null,
userImg: null,
scale: 0.9,
baseScale: 1,
rotation: 0,
posX: 0,
posY: 0,
brightness: 100,
isFlipped: false,
isDragging: false,
startX: 0,
startY: 0
};
// Load Frame Image & Config
try {
const [configRes, frameImg] = await Promise.all([
fetch('config.json').then(r => r.json()),
loadImage('frame.png')
]);
config = configRes;
state.frameImg = frameImg;
if (frameImageEl) frameImageEl.src = frameImg.src;
applyConfig(config);
initAnalytics(config.analytics?.googleAnalyticsId);
resizeCanvas();
draw();
} catch (error) {
console.error('Error loading resources:', error);
}
const resizeObserver = new ResizeObserver(() => {
resizeCanvas();
});
resizeObserver.observe(posterArea);
function resizeCanvas() {
if (!canvas) return;
const rect = posterArea.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
draw();
}
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
function draw() {
if (!ctx) return;
const w = canvas.width;
const h = canvas.height;
ctx.clearRect(0, 0, w, h);
if (state.userImg) {
ctx.save();
ctx.translate(w / 2, h / 2);
// Apply Brightness via Filter
ctx.filter = `brightness(${state.brightness}%)`;
// Apply zoom
ctx.scale(state.scale, state.scale);
// Apply Flip
if (state.isFlipped) {
ctx.scale(-1, 1);
}
// Apply rotation
ctx.rotate((state.rotation * Math.PI) / 180);
// Apply pan
ctx.translate(state.posX, state.posY);
// Draw image centered
const imgW = state.userImg.naturalWidth;
const imgH = state.userImg.naturalHeight;
ctx.drawImage(state.userImg, -imgW / 2, -imgH / 2);
ctx.restore();
}
// Update UI displays
if (zoomValDisplay) zoomValDisplay.textContent = Math.round((state.scale / state.baseScale) * 100) + '%';
if (rotateValDisplay) rotateValDisplay.textContent = state.rotation + '°';
if (brightValDisplay) brightValDisplay.textContent = state.brightness + '%';
}
function applyConfig(data) {
if (!data) return;
const fields = {
'title': data.content.title,
'subtitle': data.content.subtitle,
'description': data.content.description,
'whatsappNumber': data.content.whatsappNumber,
'whatsappText': data.content.whatsappText
};
for (const [id, val] of Object.entries(fields)) {
const el = document.getElementById(id);
if (el) el.textContent = val;
}
if (document.getElementById('whatsappLink')) {
document.getElementById('whatsappLink').href = `https://wa.me/88${data.content.whatsappNumber.replace(/-/g, '')}`;
}
if (document.getElementById('campaignBanner')) {
document.getElementById('campaignBanner').src = data.content.bannerUrl || 'banner.jpg';
}
const instructionList = document.getElementById('instructionList');
if (instructionList && data.content.instructions) {
instructionList.innerHTML = data.content.instructions.map((text, i) => `
<li class="instruction-item d-flex align-items-start gap-2 mb-2">
<i class="bi bi-check2-circle text-warning mt-1"></i>
<span class="small text-white-50">${text}</span>
</li>
`).join('');
}
const hashtagList = document.getElementById('hashtagList');
if (hashtagList && data.content.hashtags) {
hashtagList.innerHTML = data.content.hashtags.map(tag => `
<div class="hashtag-box d-flex justify-content-between align-items-center p-2 rounded-3 mb-2">
<span class="hashtag-text small fw-bold text-white opacity-75">${tag}</span>
<button class="btn btn-sm btn-link p-0 text-warning copy-btn" data-tag="${tag}">
<i class="bi bi-copy"></i>
</button>
</div>
`).join('');
hashtagList.querySelectorAll('.copy-btn').forEach(btn => {
btn.onclick = () => copyToClipboard(btn.dataset.tag);
});
}
}
imageInput.onchange = async (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = async (event) => {
state.userImg = await loadImage(event.target.result);
// Reset State
state.posX = 0;
state.posY = 0;
state.rotation = 0;
state.brightness = 100;
state.isFlipped = false;
if (brightSlider) brightSlider.value = 100;
if (rotateSlider) rotateSlider.value = 0;
const frameW = canvas.width;
const frameH = canvas.height;
const imgW = state.userImg.naturalWidth;
const imgH = state.userImg.naturalHeight;
const scaleW = frameW / imgW;
const scaleH = frameH / imgH;
state.baseScale = Math.max(scaleW, scaleH);
state.scale = state.baseScale * 1.05; // Default slightly zoomed in for better fit
zoomSlider.value = 1.05;
draw();
// UI Transitions
controlsPanel.classList.remove('hidden');
downloadBtn.classList.remove('hidden');
innerUploadPlaceholder.classList.add('hidden');
primaryUploadBtn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i> অন্য ছবি দিন';
// Mobile specific
if (window.innerWidth < 992) {
stickyMobileActions.classList.remove('hidden');
document.getElementById('mainActionButtons').classList.add('hidden');
// Smooth scroll to controls
setTimeout(() => {
controlsPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 500);
}
};
reader.readAsDataURL(file);
}
};
// Interaction Handlers
function handleStart(x, y) {
if (!state.userImg) return;
state.isDragging = true;
state.startX = x - state.posX;
state.startY = y - state.posY;
canvas.style.cursor = 'grabbing';
}
function handleMove(x, y) {
if (!state.isDragging) return;
state.posX = x - state.startX;
state.posY = y - state.startY;
draw();
}
function handleEnd() {
state.isDragging = false;
canvas.style.cursor = 'move';
}
canvas.addEventListener('mousedown', e => handleStart(e.offsetX, e.offsetY));
window.addEventListener('mousemove', e => {
if (state.isDragging) {
const rect = canvas.getBoundingClientRect();
handleMove(e.clientX - rect.left, e.clientY - rect.top);
}
});
window.addEventListener('mouseup', handleEnd);
canvas.addEventListener('touchstart', e => {
if (e.target === canvas) e.preventDefault();
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
handleStart(touch.clientX - rect.left, touch.clientY - rect.top);
}, { passive: false });
window.addEventListener('touchmove', e => {
if (state.isDragging) {
e.preventDefault();
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
handleMove(touch.clientX - rect.left, touch.clientY - rect.top);
}
}, { passive: false });
window.addEventListener('touchend', handleEnd);
// Zoom
function updateZoom(newVal) {
if (!state.userImg || !state.baseScale) return;
const val = Math.max(0.1, Math.min(3, newVal));
zoomSlider.value = val;
state.scale = state.baseScale * val;
draw();
}
zoomSlider.oninput = (e) => updateZoom(parseFloat(e.target.value));
document.getElementById('zoomIn').onclick = () => updateZoom(parseFloat(zoomSlider.value) + 0.1);
document.getElementById('zoomOut').onclick = () => updateZoom(parseFloat(zoomSlider.value) - 0.1);
// Rotation & Brightness & Flip
if (rotateSlider) rotateSlider.oninput = (e) => {
state.rotation = parseInt(e.target.value);
draw();
};
if (brightSlider) brightSlider.oninput = (e) => {
state.brightness = parseInt(e.target.value);
draw();
};
if (flipBtn) flipBtn.onclick = () => {
state.isFlipped = !state.isFlipped;
draw();
};
// D-Pad
const STEP = 5;
let moveInterval = null;
function startMoving(dx, dy) {
if (moveInterval) return;
moveInterval = setInterval(() => {
state.posX += (dx * STEP);
state.posY += (dy * STEP);
draw();
}, 16);
}
function stopMoving() { clearInterval(moveInterval); moveInterval = null; }
const dpadConfig = [
{ id: 'moveUp', dx: 0, dy: -1 },
{ id: 'moveDown', dx: 0, dy: 1 },
{ id: 'moveLeft', dx: -1, dy: 0 },
{ id: 'moveRight', dx: 1, dy: 0 }
];
dpadConfig.forEach(cfg => {
const btn = document.getElementById(cfg.id);
if (btn) {
btn.onmousedown = () => startMoving(cfg.dx, cfg.dy);
btn.onmouseup = btn.onmouseleave = stopMoving;
btn.ontouchstart = (e) => { e.preventDefault(); startMoving(cfg.dx, cfg.dy); };
btn.ontouchend = stopMoving;
}
});
// Actions
const triggerUpload = () => imageInput.click();
primaryUploadBtn.onclick = triggerUpload;
document.getElementById('reUploadBtn').onclick = triggerUpload;
mobileReupload.onclick = triggerUpload;
posterArea.onclick = () => { if (!state.userImg) triggerUpload(); };
// Export
const handleDownload = () => {
const targetSize = 1080;
const outCanvas = document.createElement('canvas');
outCanvas.width = targetSize;
outCanvas.height = targetSize;
const outCtx = outCanvas.getContext('2d');
outCtx.fillStyle = '#ffffff';
outCtx.fillRect(0, 0, targetSize, targetSize);
const ratio = targetSize / canvas.width;
if (state.userImg) {
outCtx.save();
outCtx.translate(targetSize / 2, targetSize / 2);
// Apply Filters to Export
outCtx.filter = `brightness(${state.brightness}%)`;
outCtx.scale(state.scale * ratio, state.scale * ratio);
if (state.isFlipped) outCtx.scale(-1, 1);
outCtx.rotate((state.rotation * Math.PI) / 180);
outCtx.translate(state.posX, state.posY);
const imgW = state.userImg.naturalWidth;
const imgH = state.userImg.naturalHeight;
outCtx.drawImage(state.userImg, -imgW / 2, -imgH / 2);
outCtx.restore();
}
if (state.frameImg) {
outCtx.drawImage(state.frameImg, 0, 0, targetSize, targetSize);
}
const link = document.createElement('a');
link.download = 'election-poster-2024.png';
link.href = outCanvas.toDataURL('image/png', 1.0);
link.click();
};
downloadBtn.onclick = handleDownload;
mobileDownload.onclick = handleDownload;
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
const btn = document.querySelector(`.copy-btn[data-tag="${text}"]`);
const icon = btn.querySelector('i');
icon.classList.replace('bi-copy', 'bi-check2');
setTimeout(() => icon.classList.replace('bi-check2', 'bi-copy'), 2000);
});
}
function initAnalytics(id) {
if (!id || id === 'G-XXXXXXXXXX') return;
const script1 = document.createElement('script');
script1.async = true;
script1.src = `https://www.googletagmanager.com/gtag/js?id=${id}`;
document.head.appendChild(script1);
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
window.gtag = gtag;
gtag('js', new Date());
gtag('config', id);
}
});