-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrawText.js
900 lines (735 loc) · 29.2 KB
/
drawText.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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/* To do list:
Pause/play animation button?
Allow video background. Need to draw video behind the canvas and then mux??
Randomize inputs function
Gif export
Curate fonts -- delete some and add other fonts from google fonts
Font for different languages?
Better hotkey method (user will be typing alot)
Movie posters / famous quotes -- Blade Runner, wong kar wai, etc.
Organize options in basic options / funky options -- auto-hide funky options
Button to choose lock aspect ratio when changing canvas dimensions
Force stroke to finish even on high speed?
Can background be a generative animation? This would require a background canvas/foreground?
Mobile issues:
- input table too wide (shrink input image button)
- text area doesn't update after clicking 'done', need to hit return
*/
var animation = document.getElementById("animation");
animation.addEventListener("click",refresh);
var canvasWidthInput = document.getElementById("canvasWidthInput");
canvasWidthInput.addEventListener("change",refresh);
var canvasWidth;
var canvasHeightInput = document.getElementById("canvasHeightInput");
canvasHeightInput.addEventListener("change",refresh);
var canvasHeight;
var animationfps=45;
var animationInterval;
var playAnimationToggle = false;
var xPaddingInput = document.getElementById("xPaddingInput");
xPaddingInput.addEventListener("change",refresh);
var xPadding;
var yPaddingInput = document.getElementById("yPaddingInput");
yPaddingInput.addEventListener("change",refresh);
var yPadding;
var textInput = document.getElementById("textInput");
textInput.addEventListener("change",refresh);
var text;
var colorInput = document.getElementById("colorInput");
colorInput.addEventListener("change",refresh);
var color;
var backgroundChoiceInput = document.getElementById("backgroundChoiceInput");
backgroundChoiceInput.addEventListener("change",refresh);
var backgroundChoice;
var backgroundColorInput = document.getElementById("backgroundColorInput");
backgroundColorInput.addEventListener("change",refresh);
var backgroundColor;
var fontSizeInput = document.getElementById("fontSizeInput");
fontSizeInput.addEventListener("change",refresh);
var fontSize;
var speedInput = document.getElementById("speedInput");
speedInput.addEventListener("change",refresh);
var speed;
var wavyInput = document.getElementById("wavyInput");
wavyInput.addEventListener("change",refresh);
var wavyFactor;
var colorRangeInput = document.getElementById("colorRangeInput");
colorRangeInput.addEventListener("change",refresh);
var colorRange;
var lineWidthInput = document.getElementById("lineWidthInput");
lineWidthInput.addEventListener("change",refresh);
var lineWidth;
var opacityInput = document.getElementById("opacityInput");
opacityInput.addEventListener("change",refresh);
var opacity;
var fontInput = document.getElementById("fontInput");
fontInput.addEventListener("change",refresh);
var font;
var randomXDeltaInput = document.getElementById("randomXDeltaInput");
randomXDeltaInput.addEventListener("change",refresh);
var randomXDelta;
var randomYDeltaInput = document.getElementById("randomYDeltaInput");
randomYDeltaInput.addEventListener("change",refresh);
var randomYDelta;
var randomRotationInput = document.getElementById("randomRotationInput");
randomRotationInput.addEventListener("change",refresh);
var randomRotation;
var fillCheckbox = document.getElementById('fillCheckbox');
fillCheckbox.addEventListener('click', refresh);
var fillLetterToggle = false;
var x;
var y;
var initialDashLen;
var ctx = animation.getContext("2d");
ctx.lineJoin = "round";
var originalImg = document.getElementById("originalImg");
var imageFileInput = document.getElementById('imageFileInput');
imageFileInput.addEventListener('change', readSourceImage);
var isImageLoaded = false;
var imageContainer = document.getElementById('imageContainer');
var backgroundColorInputCell = document.getElementById('backgroundColorInputCell');
var imageInputCell = document.getElementById('imageInputCell');
var videoInputCell = document.getElementById('videoInputCell');
var actualWidth = 1536; //dimensions of default image
var actualHeight = 1536;
var scaledWidth = actualWidth;
var scaledHeight = actualHeight;
var widthScalingRatio = 1;
var maxImageWidth = Math.min(window.innerWidth,4000); //can be tweaked
//detect user browser
var ua = navigator.userAgent;
var isSafari = false;
var isFirefox = false;
var isIOS = false;
var isAndroid = false;
if(ua.includes("Safari")){
isSafari = true;
}
if(ua.includes("Firefox")){
isFirefox = true;
}
if(ua.includes("iPhone") || ua.includes("iPad") || ua.includes("iPod")){
isIOS = true;
}
if(ua.includes("Android")){
isAndroid = true;
}
console.log("isSafari: "+isSafari+", isFirefox: "+isFirefox+", isIOS: "+isIOS+", isAndroid: "+isAndroid);
//save image button
var saveImageButton = document.getElementById("saveImageButton");
saveImageButton.addEventListener('click', saveImage);
//video recording function
var recordBtn = document.getElementById("recordVideoButton");
var recording = false;
var mediaRecorder;
var recordedChunks;
recordBtn.addEventListener('click', chooseRecordingFunction);
var finishedBlob;
var recordingMessageDiv = document.getElementById("videoRecordingMessageDiv");
var recordVideoState = false;
var videoRecordInterval;
var videoEncoder;
var muxer;
var mobileRecorder;
var videofps = 15;
//user input text metrics;
var numWords;
var wordLengthArray = [];
var wordStartPositionArray = [];
/*
//randomize inputs button
var randomizeButton = document.getElementById("randomizeButton");
randomizeButton.addEventListener('click', randomizeInputs);
*/
function getUserInputs(){
canvasWidth = Number(canvasWidthInput.value);
canvasHeight = Number(canvasHeightInput.value);
console.log("Canvas width / height: "+canvasWidth+", "+canvasHeight);
animation.width = canvasWidth;
animation.height = canvasHeight;
text = String(textInput.value);
text = cleanText(text);
console.log("Cleaned user text: "+text);
getTextMetrics(text);
color = String(colorInput.value);
backgroundChoice = String(backgroundChoiceInput.value)
backgroundColor = String(backgroundColorInput.value);
//set background color of the canvas
if(backgroundChoice == "solid"){
ctx.globalAlpha = 1;
ctx.fillStyle = backgroundColor;
ctx.fillRect(0,0,canvasWidth, canvasHeight);
backgroundColorInputCell.classList.remove("hidden");
imageInputCell.classList.add("hidden");
videoInputCell.classList.add("hidden");
} else if(backgroundChoice == "transparent"){
ctx.fillStyle = 'rgba(0, 0, 0, 0)';
ctx.fillRect(0,0,canvasWidth, canvasHeight);
backgroundColorInputCell.classList.add("hidden");
imageInputCell.classList.add("hidden");
videoInputCell.classList.add("hidden");
} else if(backgroundChoice == "image"){
ctx.drawImage(originalImg, 0, 0, canvasWidth, canvasHeight);
backgroundColorInputCell.classList.add("hidden");
imageInputCell.classList.remove("hidden");
videoInputCell.classList.add("hidden");
} else if(backgroundChoice == "video"){
ctx.fillStyle = 'rgba(0, 0, 0, 0)';
ctx.fillRect(0,0,canvasWidth, canvasHeight);
backgroundColorInputCell.classList.add("hidden");
imageInputCell.classList.add("hidden");
videoInputCell.classList.remove("hidden");
}
ctx.strokeStyle = ctx.fillStyle = color;
lineWidth = Number(lineWidthInput.value);
ctx.lineWidth = lineWidth;
opacity = Number(opacityInput.value);
ctx.globalAlpha = opacity/100;
xPadding = Math.round(Number(xPaddingInput.value)/100*canvasWidth);
yPadding = Math.round(Number(yPaddingInput.value)/100*canvasHeight);
font = String(fontInput.value);
fontSize = Number(fontSizeInput.value)
ctx.font = fontSize+"px "+font;
initialDashLen = fontSize * 4;
speed = Number(speedInput.value)/100 * initialDashLen/1.5;
wavyFactor = Number(wavyInput.value);
colorRange = Number(colorRangeInput.value);
randomXDelta = Number(randomXDeltaInput.value);
randomYDelta = Number(randomYDeltaInput.value) / 2;
randomRotation = Number(randomRotationInput.value) / 200;
if(fillCheckbox.checked){
fillLetterToggle = true;
} else{
fillLetterToggle = false;
}
}
function refresh(){
console.log("refresh");
if(playAnimationToggle == true){
clearInterval(animationInterval); //stop animation
playAnimationToggle = false;
}
ctx.clearRect(0, 0, canvasWidth, canvasHeight); //clear entire canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.rotate(0);
getUserInputs();
setTimeout(drawText,300);
}
//MAIN METHOD
canvasWidthInput.value = Math.floor(window.innerWidth);
canvasHeightInput.value = Math.floor(window.innerHeight/2);
fontSizeInput.value = Math.floor(Math.min(100,window.innerWidth/12));
setTimeout(getUserInputs,1800);
setTimeout(drawText,2200); //wait for fonts to load
function drawText(){
//clear any animation if one was running before
if(playAnimationToggle == true){
clearInterval(animationInterval);
playAnimationToggle = false;
}
playAnimationToggle = true;
dashLen = initialDashLen, dashOffset = dashLen, x = xPadding, i = 0;
let metrics = ctx.measureText(text);
let textHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
var textWidth = metrics.width;
console.log("textWidth: "+textWidth+", textHeight: "+textHeight);
y = textHeight+yPadding;
var rowCounter=1;
var middleYPosition = y;
animationInterval = setInterval(loop,1000/animationfps); //start loop
var currentWordWidth = 0;
var currentWordCounter = 0;
var currentWordCharLength = 0;
var currentWordWidth = 0;
var lineBreakFlag = false;
var lineBreakThreshold = 0.98;
function loop(){
if(!playAnimationToggle){
return;
}
var ch = text[i];
var chWidth = ctx.measureText(ch).width;
//calculate if the next word should start on a new line
if(dashOffset == dashLen){
//console.log("current char number: "+i);
lineBreakFlag = false;
if(wordStartPositionArray.indexOf(i) >= 0){
//this char is the start of a word
currentWordWidth = 0;
currentWordCounter++;
currentWordCharLength = wordLengthArray[currentWordCounter-1];
//console.log("start of word, with char length of "+currentWordCharLength);
for(var z=0; z<currentWordCharLength; z++){
currentWordWidth += ctx.measureText(text[i+z]).width;
}
//console.log("current word width: "+currentWordWidth);
if(currentWordWidth > canvasWidth){
lineBreakFlag = false; //let really long words pass as they break any line
} else {
if(x+currentWordWidth > (canvasWidth*lineBreakThreshold)){
lineBreakFlag = true; //create line break if word spills over the right edge
}
}
}
}
//create line break and tweak color if next char will spill over the right or top
if(lineBreakFlag == true || x+chWidth>(canvasWidth*lineBreakThreshold) || (y-textHeight/2) < 0){
x = canvasWidth*0.02; //initial xposition of new line -- can be tweaked
rowCounter++;
middleYPosition = (textHeight+ctx.lineWidth)*1.05*rowCounter + yPadding;
tweakCanvasColor();
lineBreakFlag = false; //do not do two line breaks in a row
}
var sineShift = Math.sin((x/canvasWidth)*Math.PI*2) * wavyFactor;
y = middleYPosition + sineShift;
//draw stroke line of current character
ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
if(dashOffset > 1 && dashOffset-speed <=0){
speed = dashOffset; //force stroke to finish if overshoot would happen
}
dashOffset -= speed; // reduce dash length
ctx.strokeText(ch, x, y); // stroke letter
if (dashOffset <= 0){ //once letter stroke is finished, move to next char
speed = Number(speedInput.value)/100 * initialDashLen/1.5; //reset speed back to initial value
if(fillLetterToggle){
ctx.fillText(ch, x, y); // fill final letter
}
var posOrNeg;
if(Math.random()<0.5){
posOrNeg = -1;
}else{
posOrNeg = 1;
}
x += chWidth + ctx.lineWidth + (randomXDelta * Math.random())*posOrNeg; //random x-delta
i++; //go to next char
ch = text[i];
ctx.setTransform(1, 0, 0, 1, 0, Math.random() * randomYDelta); // random y-delta
ctx.rotate(Math.random() * randomRotation); // random rotation
if((ch == ' ') || (ch == '\t') || (ch == '\n')){
dashOffset = dashLen/2; //small pause if whitespace
} else {
dashOffset = dashLen; // prep next char
}
/*
var charCounter = 0;
//find width of current word
for(var j=i; j<text.length; j++){
if(text[j] == ' '){
break;
} else {
charCounter++;
}
}
//console.log("char count: "+charCounter);
currentWordWidth = 0;
for(var z=0; z<charCounter; z++){
var currentCh = text[i+z];
currentWordWidth += ctx.measureText(currentCh).width;
}
if(currentWordWidth>=canvasWidth){
currentWordWidth=0; //allow very large words to pass the break
}
*/
//stop animation
if (i >= text.length || y > (canvasHeight*1.1)){
console.log("stop animation");
clearInterval(animationInterval);
playAnimationToggle = false;
if(recordVideoState == true){
console.log("stop video record");
setTimeout(chooseEndRecordingFunction,4000);
}
}
}
}
}
//HELPER FUNCTIONS BELOW
//read and accept user input image
function readSourceImage(){
//remove any existing images
while (imageContainer.firstChild) {
imageContainer.removeChild(imageContainer.firstChild);
}
if(playAnimationToggle == true){
clearInterval(animationInterval);
playAnimationToggle = false;
}
//read image file
var file = imageFileInput.files[0];
var reader = new FileReader();
reader.onload = (event) => {
var imageData = event.target.result;
var image = new Image();
image.src = imageData;
image.onload = () => {
actualWidth = image.width;
actualHeight = image.height;
//image scaling
if(actualWidth > maxImageWidth){
scaledWidth = maxImageWidth;
widthScalingRatio = scaledWidth / actualWidth;
scaledHeight = actualHeight * widthScalingRatio;
} else{
scaledWidth = actualWidth;
widthScalingRatio = 1;
scaledHeight = actualHeight;
}
canvasWidthInput.value = scaledWidth;
canvasHeightInput.value = scaledHeight;
//resize the src variable of the original image
var newCanvas = document.createElement('canvas');
newCanvas.width = Math.floor(scaledWidth/2)*2; //video encoder doesn't accept odd numbers
newCanvas.height = Math.floor(scaledHeight/8)*8; //video encoder wants a multiple of 8
var ctx = newCanvas.getContext('2d');
ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight);
var resizedImgSrc = newCanvas.toDataURL();
//draw the resized image onto the page
originalImg = document.createElement('img');
originalImg.setAttribute("id", "originalImg");
originalImg.src = resizedImgSrc;
originalImg.width = scaledWidth;
originalImg.height = scaledHeight;
imageContainer.appendChild(originalImg);
setTimeout(refresh,1000);
animation.scrollIntoView({ behavior: "smooth" });
};
};
reader.readAsDataURL(file);
isImageLoaded = true;
}
videoFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
const url = URL.createObjectURL(file);
video.src = url;
video.addEventListener('loadedmetadata', () => {
video.width = video.videoWidth;
video.height = video.videoHeight;
});
setTimeout(function(){
video.play();
canvasWidthInput.value = video.videoWidth;
canvasHeightInput.value = video.videoHeight;
refresh();
},2000);
});
function saveImage(){
const link = document.createElement('a');
link.href = animation.toDataURL();
const date = new Date();
const filename = `typewriter_${date.toLocaleDateString()}_${date.toLocaleTimeString()}.png`;
link.download = filename;
link.click();
}
function tweakCanvasColor(){
var currentHex = ctx.fillStyle;
//console.log("current color: "+currentHex);
var currentRGB = hexToRgb(currentHex);
var newR = currentRGB.r - colorRange/2 + Math.random()*colorRange;
var newG = currentRGB.g - colorRange/2 + Math.random()*colorRange;
var newB = currentRGB.b - colorRange/2 + Math.random()*colorRange;
var newHex = rgbToHex(newR, newG, newB);
ctx.fillStyle = newHex;
ctx.strokeStyle = newHex;
//console.log("new color: "+newHex);
}
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return { r, g, b };
}
function rgbToHex(r, g, b) {
return "#" + ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
}
//shortcut hotkey presses
document.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
refresh();
}
/*
else if (event.key === 's') {
saveImage();
} else if (event.key === 'r') {
chooseRecordingFunction();
} else if (event.key === 'i') {
randomizeInputs();
}
*/
});
function chooseRecordingFunction(){
animation.scrollIntoView({ behavior: "smooth" });
if(isIOS || isAndroid || isFirefox){
startMobileRecording();
}else {
recordVideoMuxer();
//startMobileRecording();
}
}
function chooseEndRecordingFunction(){
if(isIOS || isAndroid || isFirefox){
mobileRecorder.stop();
}else {
finalizeVideo();
//finalizeMobileVideo(mobileRecorder);
}
}
//record html canvas element and export as mp4 video
//source: https://devtails.xyz/adam/how-to-save-html-canvas-to-mp4-using-web-codecs-api
async function recordVideoMuxer() {
console.log("start muxer video recording");
var videoWidth = Math.floor(animation.width/2)*2;
var videoHeight = Math.floor(animation.height/8)*8; //force a number which is divisible by 8
console.log("Video dimensions: "+videoWidth+", "+videoHeight);
//display user message
//recordingMessageCountdown(videoDuration);
recordingMessageDiv.classList.remove("hidden");
recordVideoState = true;
const ctx = animation.getContext("2d", {
// This forces the use of a software (instead of hardware accelerated) 2D canvas
// This isn't necessary, but produces quicker results
willReadFrequently: true,
// Desynchronizes the canvas paint cycle from the event loop
// Should be less necessary with OffscreenCanvas, but with a real canvas you will want this
desynchronized: true,
});
muxer = new Mp4Muxer.Muxer({
target: new Mp4Muxer.ArrayBufferTarget(),
//let muxer = new Muxer({
//target: new ArrayBufferTarget(),
video: {
// If you change this, make sure to change the VideoEncoder codec as well
codec: "avc",
width: videoWidth,
height: videoHeight,
},
// mp4-muxer docs claim you should always use this with ArrayBufferTarget
fastStart: "in-memory",
});
videoEncoder = new VideoEncoder({
output: (chunk, meta) => muxer.addVideoChunk(chunk, meta),
error: (e) => console.error(e),
});
// This codec should work in most browsers
// See https://dmnsgn.github.io/media-codecs for list of codecs and see if your browser supports
videoEncoder.configure({
codec: "avc1.42003e",
width: videoWidth,
height: videoHeight,
bitrate: 10_000_000,
bitrateMode: "constant",
});
//NEW codec: "avc1.42003e",
//ORIGINAL codec: "avc1.42001f",
//recordVideoState = true;
var frameNumber = 0;
//setTimeout(finalizeVideo,1000*videoDuration+200); //finish and export video after x seconds
refresh();
//take a snapshot of the canvas every x miliseconds and encode to video
videoRecordInterval = setInterval(
function(){
if(recordVideoState == true){
renderCanvasToVideoFrameAndEncode({
animation,
videoEncoder,
frameNumber,
videofps
})
frameNumber++;
}else{
}
} , 1000/videofps);
}
//finish and export video
async function finalizeVideo(){
console.log("finalize muxer video");
recordVideoState = false;
clearInterval(videoRecordInterval);
// Forces all pending encodes to complete
await videoEncoder.flush();
muxer.finalize();
let buffer = muxer.target.buffer;
finishedBlob = new Blob([buffer]);
downloadBlob(new Blob([buffer]));
//hide user message
recordingMessageDiv.classList.add("hidden");
}
async function renderCanvasToVideoFrameAndEncode({
canvas,
videoEncoder,
frameNumber,
videofps,
}) {
let frame = new VideoFrame(animation, {
// Equally spaces frames out depending on frames per second
timestamp: (frameNumber * 1e6) / videofps,
});
// The encode() method of the VideoEncoder interface asynchronously encodes a VideoFrame
videoEncoder.encode(frame);
// The close() method of the VideoFrame interface clears all states and releases the reference to the media resource.
frame.close();
}
function downloadBlob() {
console.log("download video");
let url = window.URL.createObjectURL(finishedBlob);
let a = document.createElement("a");
a.style.display = "none";
a.href = url;
const date = new Date();
const filename = `typewriter_${date.toLocaleDateString()}_${date.toLocaleTimeString()}.mp4`;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
//record and download videos on mobile devices
function startMobileRecording(){
var stream = animation.captureStream(videofps);
mobileRecorder = new MediaRecorder(stream, { 'type': 'video/mp4' });
mobileRecorder.addEventListener('dataavailable', finalizeMobileVideo);
console.log("start simple video recording");
console.log("Video dimensions: "+animation.width+", "+animation.height);
//display user message
//recordingMessageCountdown(videoDuration);
recordingMessageDiv.classList.remove("hidden");
recordVideoState = true;
refresh(); //start animation
mobileRecorder.start(); //start mobile video recording
/*
setTimeout(function() {
recorder.stop();
}, 1000*videoDuration+200);
*/
}
function finalizeMobileVideo(e) {
setTimeout(function(){
console.log("finish simple video recording");
recordVideoState = false;
/*
mobileRecorder.stop();*/
var videoData = [ e.data ];
finishedBlob = new Blob(videoData, { 'type': 'video/mp4' });
downloadBlob(finishedBlob);
//hide user message
recordingMessageDiv.classList.add("hidden");
},500);
}
//finish and export video
async function finalizeVideo(){
console.log("finalize muxer video");
recordVideoState = false;
clearInterval(videoRecordInterval);
// Forces all pending encodes to complete
await videoEncoder.flush();
muxer.finalize();
let buffer = muxer.target.buffer;
finishedBlob = new Blob([buffer]);
downloadBlob(new Blob([buffer]));
//hide user message
recordingMessageDiv.classList.add("hidden");
}
function recordWhitespaces(text){
var whitespacePositions = []
for (let i = 0; i < text.length; i++) {
if (text[i] === ' ') {
whitespacePositions.push(i);
}
}
return whitespacePositions;
}
function cleanText(oldText){
var newText = "";
var oldNumChars = oldText.length;
//replace tab and new line with whitespace instead
for(var i=0; i<oldNumChars; i++){
var currentChar = '';
if(oldText[i] == '\n' || oldText[i] == '\t'){
currentChar = ' ';
} else {
currentChar = oldText[i];
}
newText = newText + currentChar;
}
return newText;
}
function getTextMetrics(userText){
numChars = userText.length;
numWords = 0;
wordLengthArray = [];
wordStartPositionArray = [];
var currentWordLength = 0;
var previousChar;
for(var i=0; i<numChars; i++){
var currentChar = userText[i];
if(currentChar == ' '){
if(i==0){
//first char is whitespace
break;
} else {
previousChar = userText[i-1];
if(previousChar != ' '){
//found the end of a word
wordLengthArray[numWords-1] = currentWordLength;
currentWordLength = 0;
}
}
}
if(currentChar != ' '){
currentWordLength++;
if(i==0){
//found the start of a word;
numWords++;
wordStartPositionArray[numWords-1] = i;
} else {
previousChar = userText[i-1];
if(previousChar != ' '){
//found the continuation of a word
if(i==(numChars-1)){
//found the end of a word given it is the end of the sentence
wordLengthArray[numWords-1] = currentWordLength;
currentWordLength = 0;
}
} else {
//found the start of a word;
numWords++;
wordStartPositionArray[numWords-1] = i;
}
}
}
}
console.log("numWords: "+numWords);
console.log("word length array: "+wordLengthArray);
console.log("word start position array: "+wordStartPositionArray);
}
/*
function randomizeInputs(){
speedInput.value = Math.ceil(Math.pow(Math.random(),2)*100);
xFreqInput.value = Math.ceil(Math.random()*50);
yFreqInput.value = Math.ceil(Math.random()*50);
xAmpInput.value = Math.ceil(Math.random()*100);
yAmpInput.value = Math.ceil(Math.random()*100);
getUserInputs();
}
*/
/*
//ORIGINAL ANIMATION ALGORITHM
//SOURCE: https://stackoverflow.com/questions/29911143/how-can-i-animate-the-drawing-of-text-on-a-web-page
function drawText(){
//ctx.clearRect(x, 0, 60, 150);
ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
dashOffset -= speed; // reduce dash length
ctx.strokeText(text[i], x, initialYOffset); // stroke letter
if (dashOffset > 0){
requestAnimationFrame(drawText); // animate
} else {
ctx.fillText(text[i], x, initialYOffset); // fill final letter
dashOffset = dashLen;
i++; // prep next char
x += ctx.measureText(text[i]).width + ctx.lineWidth * Math.random();
ctx.setTransform(1, 0, 0, 1, 0, Math.random() * randomYDelta); // random y-delta
ctx.rotate(Math.random() * randomRotation); // random rotation
if (i < text.length){
requestAnimationFrame(drawText);
}
}
}
*/