-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
390 lines (333 loc) · 15.8 KB
/
index.js
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
import Gallery from './db.js';
document.addEventListener('DOMContentLoaded', async () => {
const gallery = new Gallery('galleryDB', 1);
await gallery.init();
// Define ScalableTextbox
fabric.ScalableTextbox = fabric.util.createClass(fabric.Textbox, {
type: 'scalableTextbox',
initialize: function(text, options) {
options || (options = {});
this.callSuper('initialize', text, options);
},
_renderText: function(ctx) {
this.callSuper('_renderText', ctx);
ctx.scale(1 / this.scaleX, 1 / this.scaleY);
}
});
// Initialize Fabric.js canvas
var canvas = new fabric.Canvas('comic-artboard');
// Load canvas from localStorage or initialize with random content
await loadCanvasState(canvas, gallery);
// Retrieve stored fonts from localStorage
var storedFonts = JSON.parse(localStorage.getItem('customFonts')) || [];
// Function to save canvas state to localStorage as SVG
function saveCanvasState() {
const svg = canvas.toSVG();
localStorage.setItem('canvasStateSVG', svg);
}
// Function to load canvas state from localStorage or initialize with random content
async function loadCanvasState(canvas, gallery) {
const savedCanvasSVG = localStorage.getItem('canvasStateSVG');
if (savedCanvasSVG) {
fabric.loadSVGFromString(savedCanvasSVG, function(objects, options) {
canvas.clear();
canvas.add(...objects);
canvas.renderAll();
});
} else {
// If canvas is empty, add a random image and text
const randomImage = await gallery.getRandomImage();
if (randomImage) {
fabric.Image.fromURL(randomImage.imageData, function(img) {
img.scaleToWidth(canvas.width * 0.7);
img.scaleToHeight(canvas.height * 0.7);
img.set({
left: canvas.width / 2,
top: canvas.height / 2,
originX: 'center',
originY: 'center'
});
canvas.add(img);
// Add hello in an Indian language
const indianGreetings = ['नमस्ते', 'வணக்கம்', 'ನಮಸ್ಕಾರ', 'നമസ്കാരം'];
const randomGreeting = indianGreetings[Math.floor(Math.random() * indianGreetings.length)];
const text = new fabric.ScalableTextbox(randomGreeting, {
left: canvas.width / 2,
top: 50,
fontSize: 40,
fontFamily: 'Arial',
fill: '#000000',
originX: 'center',
originY: 'center',
width: 200,
textAlign: 'center'
});
canvas.add(text);
canvas.renderAll();
saveCanvasState();
});
}
}
}
// Add event listener for canvas modifications
canvas.on('object:modified', saveCanvasState);
canvas.on('object:added', saveCanvasState);
canvas.on('object:removed', saveCanvasState);
canvas.on('text:changed', saveCanvasState);
// Function to delete selected item
function deleteSelectedItem() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.remove(activeObject);
canvas.renderAll();
} else {
alert('Please select an item to delete.');
}
}
// Function to clear all items from canvas
function clearCanvas() {
if (confirm('Are you sure you want to clear all items from the canvas?')) {
canvas.clear();
canvas.renderAll();
localStorage.removeItem('canvasStateSVG');
}
}
// Function to populate font select dropdown
function populateFontSelect() {
var fontSelect = document.getElementById('fontSelector');
fontSelect.innerHTML = '<option value="">Select Font</option>';
// Add default fonts
var defaultFonts = ['Arial', 'Courier', 'Georgia'];
defaultFonts.forEach(function(font) {
var option = document.createElement('option');
option.value = font;
option.textContent = font;
fontSelect.appendChild(option);
});
// Add stored custom fonts
storedFonts.forEach(function(font) {
var option = document.createElement('option');
option.value = font.family;
option.textContent = font.family;
fontSelect.appendChild(option);
});
}
// Call the function to populate font select
populateFontSelect();
// Function to make canvas responsive
function resizeCanvas() {
const container = document.querySelector('.artboard-area');
const containerWidth = container.offsetWidth;
const aspectRatio = canvas.height / canvas.width;
const newWidth = containerWidth;
const newHeight = containerWidth * aspectRatio;
canvas.setDimensions({ width: newWidth, height: newHeight });
canvas.setZoom(newWidth / 800); // 800 is the original canvas width
canvas.renderAll();
}
// Initial resize and add event listener for window resize
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Function to add image to canvas
function addImageToCanvas(imgSrc) {
fabric.Image.fromURL(imgSrc, function(img) {
// Set maximum dimensions for the image
const maxWidth = canvas.width * 0.5; // 50% of canvas width
const maxHeight = canvas.height * 0.5; // 50% of canvas height
// Calculate scale factor to fit within max dimensions
var scaleFactor = Math.min(maxWidth / img.width, maxHeight / img.height);
// Scale the image
img.scale(scaleFactor);
// Center the image on the canvas
img.set({
left: canvas.width / 2,
top: canvas.height / 2,
originX: 'center',
originY: 'center'
});
canvas.add(img);
canvas.renderAll();
});
}
// Event delegation for gallery images
document.getElementById('galleryDisplay').addEventListener('click', function(e) {
if (e.target.tagName === 'IMG') {
addImageToCanvas(e.target.src);
}
});
// Function to add text to canvas
function addTextToCanvas(text, font, size) {
var textbox = new fabric.ScalableTextbox(text, {
left: canvas.width / 2,
top: canvas.height / 2,
fontSize: size,
fontFamily: font,
fill: '#000000',
originX: 'center',
originY: 'center',
width: 200, // Set a fixed initial width
padding: 5, // Add some padding
textAlign: 'center' // Center-align the text
});
canvas.add(textbox);
canvas.setActiveObject(textbox);
canvas.renderAll();
}
// Add text button functionality
document.getElementById('addTextButton').addEventListener('click', function() {
var text = document.getElementById('input').value;
var font = document.getElementById('fontSelector').value;
var size = document.querySelector('input[type="number"]').value;
if (text && font && size) {
addTextToCanvas(text, font, parseInt(size));
} else {
alert('Please enter text, select a font, and specify a font size.');
}
});
// Image upload functionality
document.getElementById('imageUpload').addEventListener('change', function(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
var fabricImage = new fabric.Image(img);
// Set maximum dimensions for the image
const maxWidth = canvas.width * 0.5; // 50% of canvas width
const maxHeight = canvas.height * 0.5; // 50% of canvas height
// Calculate scale factor to fit within max dimensions
var scaleFactor = Math.min(maxWidth / img.width, maxHeight / img.height);
// Scale the image
fabricImage.scale(scaleFactor);
// Center the image on the canvas
fabricImage.set({
left: canvas.width / 2,
top: canvas.height / 2,
originX: 'center',
originY: 'center'
});
canvas.add(fabricImage);
canvas.renderAll();
}
img.src = event.target.result;
}
reader.readAsDataURL(file);
});
// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
});
// Download canvas as PNG with white background
document.getElementById('downloadBtn').addEventListener('click', function() {
// Get the original dimensions of the canvas
var originalWidth = canvas.width;
var originalHeight = canvas.height;
// Create a new canvas with white background
var tempCanvas = document.createElement('canvas');
var tempContext = tempCanvas.getContext('2d');
tempCanvas.width = originalWidth;
tempCanvas.height = originalHeight;
// Fill with white background
tempContext.fillStyle = 'white';
tempContext.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
// Draw the Fabric.js canvas content onto the new canvas
var dataURL = canvas.toDataURL({
format: 'png',
multiplier: 1,
width: originalWidth,
height: originalHeight
});
var img = new Image();
img.onload = function() {
tempContext.drawImage(img, 0, 0);
// Create download link
var link = document.createElement('a');
link.download = 'comic_strip.png';
link.href = tempCanvas.toDataURL('image/png');
link.click();
};
img.src = dataURL;
});
// Add event listener for delete button
document.getElementById('deleteBtn').addEventListener('click', deleteSelectedItem);
// Add event listener for clear canvas button
document.getElementById('clearCanvasBtn').addEventListener('click', clearCanvas);
let currentPage = 1;
let selectedCollection = '';
const collectionSelect = document.getElementById('collectionSelect');
const galleryDisplay = document.getElementById('galleryDisplay');
const prevPageButton = document.getElementById('prevPage');
const nextPageButton = document.getElementById('nextPage');
const currentPageSpan = document.getElementById('currentPage');
collectionSelect.addEventListener('change', () => {
selectedCollection = collectionSelect.value;
currentPage = 1;
displayGallery();
});
// Ensure "All Collections" option exists
if (!collectionSelect.querySelector('option[value=""]')) {
const allCollectionsOption = document.createElement('option');
allCollectionsOption.value = '';
allCollectionsOption.textContent = 'All Collections';
collectionSelect.insertBefore(allCollectionsOption, collectionSelect.firstChild);
}
prevPageButton.addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
displayGallery();
}
});
nextPageButton.addEventListener('click', () => {
currentPage++;
displayGallery();
});
async function populateCollectionDropdown() {
try {
// Clear existing options except the first one (All Collections)
while (collectionSelect.options.length > 1) {
collectionSelect.remove(1);
}
const collectionNames = await gallery.getCollectionNames();
collectionNames.forEach(name => {
const option = document.createElement('option');
option.value = name;
option.textContent = name;
collectionSelect.appendChild(option);
});
// Set selectedCollection to empty string (All Collections) by default
selectedCollection = '';
collectionSelect.value = '';
displayGallery();
} catch (error) {
console.error('Error fetching collection names:', error);
}
}
async function displayGallery() {
console.log("display gallery");
galleryDisplay.innerHTML = '';
try {
const { results, totalPages } = await gallery.getGalleryItems(currentPage, selectedCollection);
if (results.length === 0) {
galleryDisplay.innerHTML = '<p>No images found.</p>';
} else {
results.forEach(image => {
const imgElement = document.createElement('img');
imgElement.src = image.imageData;
imgElement.alt = image.imageName;
imgElement.classList.add('w-full', 'h-auto', 'object-cover', 'rounded');
galleryDisplay.appendChild(imgElement);
});
}
// Update pagination controls
currentPageSpan.textContent = `Page ${currentPage} of ${totalPages}`;
prevPageButton.disabled = currentPage === 1;
nextPageButton.disabled = currentPage === totalPages || results.length < gallery.ITEMS_PER_PAGE;
} catch (error) {
console.error('Error displaying gallery:', error);
galleryDisplay.innerHTML = '<p>Error loading images. Please try again.</p>';
}
}
// Initial setup
populateCollectionDropdown();
});