-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
417 lines (327 loc) · 13.3 KB
/
main.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
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
/*
______________________________________________________________________________________________
| |
| Copyright 2024 ag-sanjjeev |
| |
| The source code is licensed under MIT-style License. |
| The usage, permission and condition are applicable to this source code as per license. |
| That can be found in LICENSE file or at https://opensource.org/licenses/MIT. |
|______________________________________________________________________________________________|
*/
/*================*/
/* text scroll js */
/*================*/
/* global constants */
const inputText = document.getElementById('inputText');
const canvasWidth = document.getElementById('canvasWidth');
const canvasHeight = document.getElementById('canvasHeight');
const fontSize = document.getElementById('fontSize');
const scrollSpeed = document.getElementById('scrollSpeed');
const paddingX = document.getElementById('paddingX');
const paddingY = document.getElementById('paddingY');
const lineHeight = document.getElementById('lineHeight');
const fps = document.getElementById('fps');
const backgroundColor = document.getElementById('backgroundColor');
const textColor = document.getElementById('textColor');
const textFontFamily = document.getElementById('textFontFamily');
const setFontButton = document.getElementById('setFontButton');
const fontStyle = document.getElementById('fontStyle');
const textAlignment = document.getElementById('textAlignment');
const playButton = document.getElementById('playButton');
const previewDownloadButton = document.getElementById('previewDownloadButton');
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth / 5;
canvas.height = window.innerHeight / 2;
canvas.style.backgroundColor = backgroundColor.value;
// Initially set recorder state to null
let recorderState = null;
/* class ScrollText */
class ScrollText {
// private property
#totalTextHeight = 0;
#wrappedText;
// constructor method
constructor (inputText) {
this.inputText = inputText.split('\n');
this.fontSize = fontSize.value;
this.scrollSpeed = scrollSpeed.value;
this.backgroundColor = backgroundColor.value;
this.textColor = textColor.value;
this.paddingX = paddingX.value;
this.paddingY = paddingY.value;
this.lineHeight = lineHeight.value;
this.fontFamily = textFontFamily.value;
this.fontStyle = fontStyle.value;
this.textAlignment = textAlignment.value;
this.interval = 1000/fps.value;
this.timer = 0;
this.recorderState = 'initialized';
this.recorder = null;
this.animationFrameReference = null;
canvas.width = canvasWidth.value;
canvas.height = canvasHeight.value;
canvas.style.backgroundColor = this.backgroundColor;
this.x = this.paddingX / 2;
this.y = 0;
this.wrapText();
this.calcTotalTextHeight();
this.currentY = canvas.height;
}
// scroll method
scroll(timeStamp) {
// setting default font if it is an empty
if (this.fontFamily == null || this.fontFamily == undefined) { this.fontFamily = 'Ysabeau Infant'; }
// clear everything in canvas before start next frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// fill background
ctx.fillStyle = this.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
let textFontStyle = this.fontStyle.replaceAll('underline', '').trim();
// setting font style
ctx.font = `${this.fontStyle} ${this.fontSize}px ${this.fontFamily}, san-serif`;
// setting initial y co-ordinate to be height of canvas
this.y = this.currentY;
// iterate through rearranged wrapped text for given details
for (const line of this.#wrappedText) {
// new temp line for processing and applying styles
let newTempLine = line;
// line width
let lineWidth = 0;
// underline height
let underlineHeight = 0;
// scrolling text fill
ctx.fillStyle = this.textColor;
// there is no text justified alignment
if (this.textAlignment != '') {
ctx.textAlign = (this.textAlignment != 'justified') ? this.textAlignment : 'left';
}
// measuring actual wrapped text width metrics in canvas context
lineWidth = ctx.measureText(line).width;
// assigning x co-ordinates for right, center and justify text alignment
if (this.textAlignment == 'right') {
this.x = (Number(this.x) + Number(canvas.width) - this.paddingX) / 2;
} else if (this.textAlignment == 'center') {
this.x = (Number(canvas.width)) / 2;
} else if (this.textAlignment == 'justified') {
// checking if it is an empty line
if (line.trim() != '') {
// getting free space width metrics
let noOfFreeSpaces = (canvas.width - this.paddingX) - lineWidth;
// proceeds only if any whitespace
if (line.indexOf(' ') !== -1) {
// getting number of whitespace in the line
let noOfWhiteSpaces = line.match(/([\s]+)/g).length;
// if it has atleast one whitespace to proceed
if (noOfFreeSpaces > 0) {
// measuring single whitespace width metric for text style
let whiteSpaceWidth = ctx.measureText(' ').width;
// calculating new white space counts
let newWhiteSpaces = Math.ceil((noOfFreeSpaces / noOfWhiteSpaces) / whiteSpaceWidth);
// appending and sharing equal whitespaces to all whitespaces in the line
let whiteSpaces = '';
for (let _i = 0; _i < newWhiteSpaces; _i++) {
whiteSpaces += ' ';
}
newTempLine = line.trim();
newTempLine = newTempLine.replace(/\s/g, whiteSpaces);
}
}
}
}
// filling text to canvas context
ctx.fillText(newTempLine, this.x, this.y);
// applying underline font style
if (this.fontStyle.indexOf('underline') !== -1) {
// default co-ordinates will be followed for left text alignment
let underlineX = this.x;
// measuring width metrics for new processed line text
lineWidth = ctx.measureText(newTempLine).width;
// setting underline color as same as text color
ctx.fillStyle = this.textColor;
// underline x co-ordinate will be differs for right and center alignment
if (this.textAlignment == 'right') {
underlineX = (canvas.width - this.paddingX) - lineWidth;
} else if (this.textAlignment == 'center') {
underlineX = Number(this.x) - Number(lineWidth / 2);
}
// filling rectangular line as an underline below to text
ctx.fillRect(underlineX, Number(this.y) + 15, lineWidth, 2);
// Setting Underline Height for next line y co-ordinate
underlineHeight = 17; // sum of 15 + 2
}
// increasing the y co-ordinate to move next line to visible area of canvas
this.y += Number(this.fontSize) + Number(this.lineHeight) + Number(underlineHeight);
// filling padding vertical area
ctx.fillStyle = this.backgroundColor;
ctx.fillRect(0, 0, canvas.width, this.paddingY/2);
ctx.fillRect(0, canvas.height - this.paddingY/2, canvas.width, this.paddingY/2);
}
// updating current y co-ordinate value
this.currentY -= this.scrollSpeed;
// reset y co-ordinate to animate again
if (Number(this.currentY) + Number(this.totalTextHeight) + Number(this.paddingY) < 0 ) {
this.currentY = canvas.height;
// if this scroll animation request by recorder event then need to stop after completing animation
if (this.recorder != null) {
this.recorder.stop();
setTimeout(this.stopAnimation.bind(this), 1000);
}
}
// saving animation reference to stop or cancelAnimationFrame
this.animationFrameReference = window.requestAnimationFrame(this.scroll.bind(this));
}
// stopAnimation method
stopAnimation () {
// canceling or stopping animation
window.cancelAnimationFrame(this.animationFrameReference);
}
// calcTotalTextHeight method
calcTotalTextHeight() {
// calculating total height that going to occupy by processed text
this.totalTextHeight = Number(this.paddingY);
for (const line of this.#wrappedText) {
this.totalTextHeight += Number(this.fontSize) + Number(this.lineHeight);
}
}
// wrapText method
wrapText() {
// getting input text split by new lines
let lines = this.inputText;
let textFontStyle = this.fontStyle.replaceAll('underline', '').trim();
// assigning font style to calculate total width and height taken in the canvas
// ctx.font = `${this.fontSize}px ${this.fontFamily}, san-serif`;
ctx.font = `${textFontStyle} ${this.fontSize}px ${this.fontFamily}, san-serif`;
// created empty lines array to store new lines
let tempLines = [];
// iterate through all lines of text that given
for (const line of lines) {
// split by space that consider as words
const words = line.split(' ');
// initialize empty current line array for each iteration
let currentLine = [];
// iterate through each word in the line
for (const word of words) {
// measuring text metrics inside canvas
const metrics = ctx.measureText(currentLine.join(' ') + word + ' ');
// calculating line width taken inclusive of padding in horizontal
const lineWidth = Number(metrics.width) + Number(this.paddingX);
// if lines width is more than the allotted width then it will be a new line
if (lineWidth >= (canvas.width - this.paddingX)) {
tempLines.push(currentLine.join(' '));
currentLine = [];
}
// pushing last line
currentLine.push(word);
}
// pushing all new processed lines into temp lines
tempLines.push(currentLine.join(' '));
}
// setting into class properties for animation
this.#wrappedText = tempLines;
}
}
/* class preference */
class PreferenceHandler {
// constructor method
constructor () {
this.isAnimationPlaying = false;
this.object = null;
this.fontFamily = null;
}
// setAnimationObject method
setAnimationObject(object) {
// setting animation object for further reference
this.object = object;
}
// getAnimationState method
getAnimationState() {
// which returns true or false set to this class properties
return this.isAnimationPlaying;
}
// getAnimationObject method
getAnimationObject() {
// which returns animation class object
return this.object;
}
}
// initializing PreferenceHandler class object
const preferenceObj = new PreferenceHandler();
setFontButton.addEventListener('click', function() {
let fontFamily = textFontFamily.value.trim();
// Basic validation (optional)
if (!fontFamily) {
return; // Handle empty input
}
// Construct the Google Fonts URL based on user input
const fontUrl = `https://fonts.googleapis.com/css2?family=${fontFamily.replaceAll(' ', '+')}:wght@300;400;700&display=swap`;
const canvasFontLink = document.getElementById('canvasFontLink');
if (canvasFontLink == null || canvasFontLink == undefined) {
// Create a new link element dynamically
const link = document.createElement('link');
link.href = fontUrl;
link.id = 'canvasFontLink';
link.rel = 'stylesheet';
link.media = 'all';
// Inject the link into the head of the document
document.head.appendChild(link);
} else {
canvasFontLink.href = fontUrl;
}
preferenceObj.fontFamily = fontFamily;
});
/* play button event listener */
playButton.addEventListener('click', function(e) {
recorderState = null;
animateScroll();
});
/* preview and download button event listener */
previewDownloadButton.addEventListener('click', function(e) {
// disabling button to avoid click when starts processing
previewDownloadButton.disabled = true;
// Capture canvas as video stream
const stream = canvas.captureStream(fps.value);
// Use MediaRecorder to record the stream
const recorder = new MediaRecorder(stream);
const videoChunks = [];
// stores stream video chunks into array of chunks
recorder.ondataavailable = (e) => videoChunks.push(e.data);
// recorder event when its stops
recorder.onstop = () => {
// creating video blob data
const videoBlob = new Blob(videoChunks, { type: 'video/webm' });
// creating video object URL to download
const videoUrl = URL.createObjectURL(videoBlob);
// Create a downloadable link
const link = document.createElement('a');
link.href = videoUrl;
link.download = 'canvas_video.webm';
link.click();
// Revoke object URL to avoid memory leaks
URL.revokeObjectURL(videoUrl);
// enabling button for next time use
previewDownloadButton.disabled = false;
};
// starting record
recorder.start();
animateScroll(recorder);
});
// animation function
function animateScroll(recorder=null) {
// if this function is called by play or preview then need to stop the canvas animation frames
if (preferenceObj.isAnimationPlaying && preferenceObj.object != null) {
preferenceObj.object.stopAnimation();
}
// getting user text input
let text = inputText.value;
// creating ScrollText class animation object
const aniObj = new ScrollText(text);
// setting recorder reference
aniObj.recorder = recorder;
// calling scroll method to start animation
aniObj.scroll(0);
// setting ScrollText class object for further reference
preferenceObj.setAnimationObject(aniObj);
// setting animation play as true means playing and false means stopping
preferenceObj.isAnimationPlaying = true;
}