-
Notifications
You must be signed in to change notification settings - Fork 2
/
kaleidoscope.js
634 lines (520 loc) · 20.2 KB
/
kaleidoscope.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
/*
To do list:
add embedded ig posts to show example gallery?
Site logo or Gradient banner at the top?
*/
//image upload variables
var animation = document.getElementById("animation");
var imageInput = document.getElementById('imageInput');
imageInput.addEventListener('change', readSourceImage);
var isImageLoaded = false;
var imageContainer = document.getElementById('imageContainer');
var newImageContainer = document.getElementById('newImageContainer');
var actualWidth = 400; //dimensions of default image
var actualHeight = 533;
var scaledWidth = 400;
var scaledHeight = 533;
var widthScalingRatio = 1;
var SqrtOf3_4 = Math.sqrt(3)/2;
var canvasWidthInput = document.getElementById("canvasWidthInput");
canvasWidthInput.addEventListener("change",changeTiling);
var canvasHeightInput = document.getElementById("canvasHeightInput");
canvasHeightInput.addEventListener("change",changeTiling);
var canvasWidth;
var canvasHeight;
var maxImageWidth;
//cover loading screen
var loadingScreen = document.getElementById("coverScreen");
//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);
//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");
//video duration input
var videoDurationInput = document.getElementById("videoDurationInput");
videoDurationInput.addEventListener('change', getUserInputs);
var videoDuration = Math.max(1,Math.min(120,Number(videoDurationInput.value)));
/*
//Save and export the new image in png format
var saveButton = document.getElementById('save-image-button');
var downloadButton = document.getElementById("downloadButton");
downloadButton.addEventListener("click",downloadBlob);
*/
//user control sliders
var animationSpeedInput = document.getElementById('speedInput');
animationSpeedInput.addEventListener('change', getUserInputs);
var userImage;
var numTilesInput = document.getElementById('numTilesInput');
numTilesInput.addEventListener('change', changeTiling);
var numTiles;
//animation variables
var animationLength = 600; //larger value give longer animation before restarting loop
var animationSpeed = 2000; //larger value gives slower animation
var counter = animationSpeed*0.5; //animation start point
var patDim = 400;
var animationWidth = 800;
var animationHeight = 800;
var animationStep = 1.5; //larger values give larger movement between animation frames;
var animationInterval;
var playAnimationToggle = false;
var animationRequest;
var fps = 30; //video record frames per second
//MAIN METHOD
//this runs the default image animation at startup
userImage = document.getElementById("originalImg");
canvasWidthInput.value = window.innerWidth;
canvasHeightInput.value = window.innerHeight;
getUserInputs();
setTimeout(createAnimation, 2000);
function refresh(){
getUserInputs();
createAnimation();
}
function getUserInputs(){
canvasWidth = Number(canvasWidthInput.value);
canvasHeight = Number(canvasHeightInput.value);
numTiles = Number(numTilesInput.value);
maxImageWidth = Math.ceil(canvasWidth/numTiles); //could be tweaked for custom output dimensions
speedInputValue = Number(animationSpeedInput.value);
animationSpeed = 8000/speedInputValue * (numTiles/2.5); //larger value gives slower animation
console.log("animation speed: "+animationSpeed);
videoDuration = Math.max(1,Math.min(60,Number(videoDurationInput.value)));
console.log("video record duration (seconds): "+videoDuration);
}
function changeTiling(){
getUserInputs();
resizeImage();
animation.scrollIntoView({behavior: "smooth", block: "start"});
createAnimation();
}
//read and accept user input image
function readSourceImage(){
//remove any existing images
while (imageContainer.firstChild) {
imageContainer.removeChild(imageContainer.firstChild);
}
while (newImageContainer.firstChild) {
newImageContainer.removeChild(newImageContainer.firstChild);
}
if(playAnimationToggle == true){
//clearInterval(animationInterval);
cancelAnimationFrame(animationRequest);
playAnimationToggle = false;
console.log("cancel animation");
}
loadingScreen.classList.remove("hidden");
loadingScreen.classList.add("lockOn");
counter = animationSpeed*0.5; //reset to default animation start point
//read image file
var file = imageInput.files[0];
var reader = new FileReader();
reader.onload = (event) => {
var imageData = event.target.result;
userImage = new Image();
userImage.src = imageData;
userImage.onload = () => {
actualWidth = userImage.width;
actualHeight = userImage.height;
resizeImage();
};
};
reader.readAsDataURL(file);
isImageLoaded = true;
}
function resizeImage(){
if(isImageLoaded){
//remove any existing images
while (imageContainer.firstChild) {
imageContainer.removeChild(imageContainer.firstChild);
}
while (newImageContainer.firstChild) {
newImageContainer.removeChild(newImageContainer.firstChild);
}
}
//image scaling dimensions
if(actualWidth > maxImageWidth){
scaledWidth = maxImageWidth;
widthScalingRatio = scaledWidth / actualWidth;
scaledHeight = actualHeight * widthScalingRatio;
} else{
scaledWidth = actualWidth;
widthScalingRatio = 1;
scaledHeight = actualHeight;
}
patDim = scaledWidth;
//resize the src variable of the original image
var newCanvas = document.createElement('canvas');
newCanvas.width = scaledWidth;
newCanvas.height = scaledHeight;
var ctx = newCanvas.getContext('2d');
ctx.drawImage(userImage, 0, 0, scaledWidth, scaledHeight);
var resizedImgSrc = newCanvas.toDataURL();
//draw the resized image onto the page
var originalImg = document.createElement('img');
originalImg.setAttribute("id", "originalImg");
originalImg.src = resizedImgSrc;
originalImg.width = scaledWidth;
originalImg.height = scaledHeight;
imageContainer.appendChild(originalImg);
setTimeout(generateFlippedImage, 1000); //wait a second for image creation before next function
}
//flip input image horizontally
function generateFlippedImage(){
console.log("generate flipped image");
var originalImg = document.getElementById('originalImg');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = originalImg.width;
canvas.height = originalImg.height;
ctx.drawImage(originalImg, 0, 0, originalImg.width, originalImg.height);
ctx.scale(-1, 1);
ctx.drawImage(canvas, -originalImg.width, 0, originalImg.width, originalImg.height);
var flippedImg = new Image();
flippedImg.setAttribute("id", "flippedImg");
flippedImg.src = canvas.toDataURL();
newImageContainer.appendChild(flippedImg);
setTimeout(createAnimation, 1000); //wait a second for image creation before next function
}
//based on Luke Hannam's work: https://www.pepperoni.blog/canvas-kaleidoscope/
function createAnimation(){
loadingScreen.classList.add("hidden");
loadingScreen.classList.remove("lockOn");
getUserInputs();
if(playAnimationToggle == true){
//clearInterval(animationInterval);
cancelAnimationFrame(animationRequest);
playAnimationToggle = false;
console.log("cancel animation");
}
playAnimationToggle = true;
console.log("create animation");
//load images
animationWidth = canvasWidth;
animationHeight = canvasHeight;
animation.width = animationWidth;
animation.height = animationHeight;
var baseImg = document.getElementById("originalImg");
var baseRImg = document.getElementById("flippedImg");
var ctx = animation.getContext("2d", { willReadFrequently: true }); //added willReadFrequently
var pat = ctx.createPattern(baseImg, "repeat");
var patR = ctx.createPattern(baseRImg, "repeat");
//height of triangle side given side length of 150 is:
//patDim = canvasWidth/2;
var height = SqrtOf3_4 * patDim;
var offset = 0;
ctx.translate(-0.5*patDim, 0);
var fn = function(alternateMode){
//offset = (offset - 1) % 1024
offset = Math.sin(counter/animationSpeed*Math.PI)*animationLength; //makes animation go forward then backwards
counter++;
var i = 0;
//draw kaleidoscope first row.
ctx.save();
ctx.fillStyle=pat;
ctx.translate(0, offset);
while(i <= 3){
ctx.beginPath();
ctx.moveTo(0,-offset);
ctx.lineTo(patDim, -offset);
ctx.lineTo(0.5*patDim, height-offset);
ctx.closePath();
//ctx.stroke(); //stroke included here helps with illustrating the draw
ctx.fill();
if(i%3==0){
ctx.translate(patDim,-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(-patDim,offset);
}
else if(i%3==1){
if(alternateMode){
ctx.rotate(120*Math.PI/180);
ctx.translate(-3*patDim, 0);
ctx.rotate(-120*Math.PI/180);
}
ctx.translate(0.5*patDim, height-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(-0.5*patDim, -height+offset);
}
else if(i%3==2){
ctx.translate(0,-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(0,offset);
}
i++;
}
ctx.restore();
ctx.save();
ctx.scale(-1,-1);
ctx.fillStyle=patR;
ctx.translate((-i+(i%3==0?0.5:i%3==1?1.5:-0.5))*patDim, -height+offset);
ctx.translate(0, -offset);
ctx.rotate(120*Math.PI/180);
ctx.translate(0, offset);
var j=0;
while(j < i+1){
ctx.beginPath();
if(j>0||!alternateMode){
ctx.moveTo(0,-offset);
ctx.lineTo(patDim, -offset);
ctx.lineTo(0.5*patDim, height-offset);
ctx.closePath();
ctx.fill();
}
if(j%3==1){
ctx.translate(patDim,-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(-patDim,offset);
}
else if(j%3==2){
ctx.translate(0.5*patDim, height-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(-0.5*patDim, -height+offset);
}
else if(j%3==0){
ctx.translate(0,-offset);
ctx.rotate(-120*Math.PI/180);
ctx.translate(0,offset);
}
j++;
}
ctx.restore();
};
var patternHeight = Math.floor(SqrtOf3_4*patDim*2);
//tile function makes the animation fill up the whole canvas width/height
var tile = function(){
var rowData = ctx.getImageData(0,0,patDim*3,patternHeight);
for(var i=0; patternHeight*i<animationHeight+SqrtOf3_4*patDim; i++){
for(var j = 0; j*patDim<animationWidth+patDim; j+=3){
ctx.putImageData(rowData,j*patDim,i*patternHeight);
}
}
}
//this creates the animation by calling the functions again and again every x miliseconds
/*
animationInterval = setInterval(
function(){
if(playAnimationToggle == true){
fn(false);
ctx.translate(animationStep*patDim, height);
fn(true);
ctx.translate(animationStep*-1*patDim, -height);
tile();
}
} , 1000/fps);
*/
function loop(){
if(playAnimationToggle == true){
fn(false);
ctx.translate(animationStep*patDim, height);
fn(true);
ctx.translate(animationStep*-1*patDim, -height);
tile();
}
animationRequest = requestAnimationFrame(loop);
}
animationRequest = requestAnimationFrame(loop);
}
//HELPER FUNCTIONS BELOW
//take screenshot of canvas at current position, export as png
//start or stop animation
function pausePlayAnimation(){
if(playAnimationToggle == true){
playAnimationToggle = false;
cancelAnimationFrame(animationRequest);
} else {
playAnimationToggle = true;
createAnimation();
}
}
function saveImage(){
const link = document.createElement('a');
link.href = animation.toDataURL();
const date = new Date();
const filename = `kaleidoscope_${date.toLocaleDateString()}_${date.toLocaleTimeString()}.png`;
link.download = filename;
link.click();
}
//shortcut hotkey presses
document.addEventListener('keydown', function(event) {
if (event.key === 'p') {
pausePlayAnimation();
} else if (event.key === 's') {
saveImage();
} else if (event.key === 'r') {
recordVideoMuxer();
}
});
function chooseRecordingFunction(){
if(isIOS || isAndroid || isFirefox){
startMobileRecording();
}else {
recordVideoMuxer();
}
}
//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);
//hide input table and display user message
document.getElementById("inputTable").classList.add("hidden");
recordingMessageCountdown(videoDuration);
recordingMessageDiv.classList.remove("hidden");
var 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,
});
let muxer = new Mp4Muxer.Muxer({
target: new Mp4Muxer.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",
});
let 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: 7_200_000,
bitrateMode: "constant",
});
//NEW codec: "avc1.42003e",
//ORIGINAL codec: "avc1.42001f",
var recordVideoState = true;
var frameNumber = 0;
setTimeout(finalizeVideo,1000*videoDuration+200); //finish and export video after x seconds
//take a snapshot of the canvas every x miliseconds and encode to video
var videoRecordInterval = setInterval(
function(){
if(recordVideoState == true){
renderCanvasToVideoFrameAndEncode({
animation,
videoEncoder,
frameNumber,
fps
})
frameNumber++;
}
} , 1000/fps);
//finish and export video after x seconds
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, show download button
recordingMessageDiv.classList.add("hidden");
document.getElementById("inputTable").classList.remove("hidden");
}
}
async function renderCanvasToVideoFrameAndEncode({
canvas,
videoEncoder,
frameNumber,
fps,
}) {
let frame = new VideoFrame(animation, {
// Equally spaces frames out depending on frames per second
timestamp: (frameNumber * 1e6) / fps,
});
// 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 = `kaleidoscope_${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(fps);
var recorder = new MediaRecorder(stream, { 'type': 'video/mp4' });
recorder.addEventListener('dataavailable', finishMobileRecording);
console.log("start simple video recording");
console.log("Video dimensions: "+animation.width+", "+animation.height);
//hide input table and display user message
document.getElementById("inputTable").classList.add("hidden");
recordingMessageCountdown(videoDuration);
recordingMessageDiv.classList.remove("hidden");
recorder.start();
setTimeout(function() {
recorder.stop();
}, 1000*videoDuration+200);
}
function finishMobileRecording(e) {
setTimeout(function(){
console.log("finish simple video recording");
var videoData = [ e.data ];
finishedBlob = new Blob(videoData, { 'type': 'video/mp4' });
downloadBlob(finishedBlob);
//hide user message, show download button
recordingMessageDiv.classList.add("hidden");
document.getElementById("inputTable").classList.remove("hidden");
},500);
}
function recordingMessageCountdown(duration){
var secondsLeft = Math.ceil(duration);
var countdownInterval = setInterval(function(){
secondsLeft--;
recordingMessageDiv.innerHTML =
"Video recording underway. The video will be saved to your downloads folder in <span id=\"secondsLeft\">"+secondsLeft+"</span> seconds.<br><br>This feature can be a bit buggy on Mobile -- if it doesn't work, please try on Desktop instead.";
if(secondsLeft <= 0){
console.log("clear countdown interval");
clearInterval(countdownInterval);
}
},1000);
}