JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
HTML
<video playsinline autoplay></video>
<canvas></canvas>
CSS
video {
display: none;
}
JavaScript
const video = document.querySelector("video");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
navigator.mediaDevices.getUserMedia({
audio: false,
video: true // { width: 426, height: 240 }
})
.then((stream) => video.srcObject = stream)
.catch(err => alert("Permission to access webcam was denied. Make sure your browser settings allow webcam access on this page."));
function renderToCanvas() {
const w = video.videoWidth;
const h = video.videoHeight;
canvas.width = w;
canvas.height = h;
ctx.drawImage(video, 0, 0);
/* ctx.strokeStyle = "red";
ctx.lineWidth = 8;
ctx.beginPath();
ctx.rect(w / 4, h / 4, w / 2, h / 2);
ctx.stroke(); */
}
function loop() {
requestAnimationFrame(loop);
renderToCanvas();
}
loop();
const WS_URL = 'ws://localhost:3001';
const FPS = 3;
const ws = new WebSocket(WS_URL);
ws.onopen = () => {
console.log(`Connected to ${WS_URL}`);
setInterval(() => {
ws.send(canvas.toDataURL('image/png'));
}, 1000 / FPS);
}