-
Notifications
You must be signed in to change notification settings - Fork 2
/
firstDraft.html
81 lines (72 loc) · 2.75 KB
/
firstDraft.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PureJS Video Element Capture</title>
</head>
<body>
<label for="interval">Time between images in seconds: </label>
<input id="interval" type="text" value="5" min="1" pattern="\d+">
<br>
<button id="start">Start</button>
<p>
Images captured: <span>0</span>
</p>
<br>
<button id="stop" disabled>Stop & Show Images</button>
<div id="images"></div>
<script>
const startBtn = document.querySelector('button#start');
const stopBtn = document.querySelector('button#stop');
const intervalSec = document.querySelector('input#interval');
const imageCountSpan = document.querySelector('span');
const imagesDiv = document.querySelector('div#images');
const imageBlobs = [];
let stream;
startBtn.onclick = async () => {
startBtn.disabled = true;
stream = await navigator.mediaDevices.getUserMedia({video: true});
const [track] = stream.getVideoTracks();
const {width, height} = track.getSettings();
const readable = (new MediaStreamTrackProcessor(track)).readable;
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext("bitmaprenderer");
let last = 0;
const queuingStrategy = new CountQueuingStrategy({highWaterMark: 1});
const writableStream = new WritableStream({
write: async frame => {
// (data check on the interval value) * that value is in seconds * frame timestamps are in microseconds
const interval = (parseInt(intervalSec.value) >= 1 ? intervalSec.value * 1: 1) * 1000 * 1000;
if (frame.timestamp > last + interval) {
ctx.drawImage(frame, 0, 0);
const blob = await canvas.convertToBlob({type: "image/jpeg"});
const blobUrl = URL.createObjectURL(blob);
console.log(frame);
imageBlobs.push(blobUrl);
imageCountSpan.innerText++;
last = frame.timestamp;
}
frame.close();
},
close: () => console.log("stream closed"),
abort: () => console.log("stream aborted"),
}, queuingStrategy);
stopBtn.disabled = false;
await readable.pipeTo(writableStream);
}
stopBtn.onclick = () => {
// close the camera
stream.getTracks().forEach(track => track.stop());
// Display each image
function showImages() {
const imgElem = new Image();
imgElem.src = imageBlobs.shift();
imagesDiv.appendChild(imgElem);
if (imageBlobs.length > 0)
showImages();
}
showImages();
}
</script>
</body>
</html>