Browse code

Add double press to toggle between "environment" and "user" camera

Robert Cranston authored on 18/07/2025 20:04:52
Showing 1 changed files

... ...
@@ -4,6 +4,7 @@ const type    = "image/jpeg";
4 4
 const quality = 0.95;
5 5
 const width   = 1920;
6 6
 const height  = 1440;
7
+const timeout = 250;
7 8
 
8 9
 const camera  = document.getElementById("camera");
9 10
 const message = document.createElement("div");
... ...
@@ -12,6 +13,7 @@ const canvas  = document.createElement("canvas")
12 13
 const ctx     = canvas.getContext("2d");
13 14
 
14 15
 let facingMode = "environment";
16
+let timer      = null;
15 17
 
16 18
 async function getVideo() {
17 19
     try {
... ...
@@ -43,8 +45,26 @@ async function post()
43 45
     }
44 46
 }
45 47
 
46
-message.innerHTML = "Press video to post.";
47
-video.addEventListener("click", post);
48
+function flip() {
49
+    facingMode = facingMode == "environment" ? "user" : "environment";
50
+    getVideo();
51
+}
52
+
53
+function timerSelector(first, second, initiate) {
54
+    return () => {
55
+        if (timer == null) {
56
+            if (initiate)
57
+                timer = setTimeout(() => { timer = null; first(); }, timeout);
58
+        } else {
59
+            clearTimeout(timer);
60
+            timer = null;
61
+            second();
62
+        }
63
+    }
64
+}
65
+
66
+message.innerHTML = "Press video to post, double press to flip.";
67
+video.addEventListener("click", timerSelector(post, flip, true));
48 68
 camera.appendChild(message);
49 69
 camera.appendChild(video);
50 70
 getVideo();