Skip to content

Instantly share code, notes, and snippets.

@brianmed
Created June 6, 2023 13:53
Show Gist options
  • Save brianmed/7d4b1a1622a9b1f7e59a5a966cdc3c9e to your computer and use it in GitHub Desktop.
Save brianmed/7d4b1a1622a9b1f7e59a5a966cdc3c9e to your computer and use it in GitHub Desktop.
Webcam in Chrome with offscreen rendering and a Worker and GetUserMedia
<html>
<head>
<title>Joy</title>
</head>
<body>
<button id="joy-button">Joy</button>
<canvas id="canvas0" width="1280" height="720"></canvas>
<script>
let canvasOffscreen = null;
let videoWorker = null;
let btn = document.querySelector("#joy-button")
btn.addEventListener("click", startCanvas);
(async function() {
canvasOffscreen = document.querySelector('#canvas0').transferControlToOffscreen();
videoWorker = new Worker('canvasWithWorkerVideo.js');
}());
async function startCanvas()
{
var constraints =
{
audio:
{
// noiseSuppression: true,
// echoCancellation: true,
channelCount: 2
},
video:
{
facingMode: "user",
width: { min: 1280, ideal: 1280, max: 1280 },
height: { min: 720, ideal: 720, max: 720 }
}
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
const videoTrack = stream.getVideoTracks()[0];
const videoTrackProcessor = new MediaStreamTrackProcessor(videoTrack);
const videoReader = videoTrackProcessor.readable;
videoWorker.postMessage({ canvasOffscreen: canvasOffscreen, videoReader: videoReader }, [canvasOffscreen, videoReader]);
}
</script>
</body>
</html>
let canvasOffscreen = null;
let canvasCtx = null;
onmessage = async (e) =>
{
canvasOffscreen = e.data.canvasOffscreen;
canvasCtx = canvasOffscreen.getContext("2d");
let videoReader = e.data.videoReader.getReader();
let videoFrameCounter = 0;
while (true)
{
const videoReaderResult = await videoReader.read();
if (videoReaderResult.done)
{
break;
}
const videoFrameFromCamera = videoReaderResult.value;
videoFrameCounter++;
canvasCtx.drawImage(videoFrameFromCamera, 0, 0);
videoFrameFromCamera.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment