Untitled
unknown
typescript
a year ago
2.2 kB
12
Indexable
import { useRef, useEffect, useState } from 'react';
interface Dot {
x: number;
y: number;
}
const VideoWithDots = () => {
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [dots, setDots] = useState<Dot[]>([]);
useEffect(() => {
const startVideo = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
if (videoRef.current) {
videoRef.current.srcObject = stream;
}
} catch (err) {
console.error('Error: ', err);
}
};
startVideo();
}, []);
// websocketi real time komunikacija
useEffect(() => {
const socket = new WebSocket('ws://backend-endpoint');
socket.onmessage = (event) => {
const newDots: Dot[] = JSON.parse(event.data);
setDots(newDots);
};
socket.onclose = () => {
console.log('WebSocket closed');
};
return () => {
socket.close();
};
}, []);
useEffect(() => {
const canvas = canvasRef.current;
const video = videoRef.current;
if (!canvas || !video) {
return;
}
const ctx = canvas.getContext('2d');
const updateCanvas = () => {
if (!ctx || !video) {
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
dots.forEach(({ x, y }) => {
ctx.beginPath();
ctx.arc(x * canvas.width, y * canvas.height, 5, 0, 2 * Math.PI); // Scale dot positions to canvas size
ctx.fillStyle = 'red';
ctx.fill();
});
requestAnimationFrame(updateCanvas);
};
requestAnimationFrame(updateCanvas);
return () => {
cancelAnimationFrame(updateCanvas);
};
}, [dots]);
return (
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
<video ref={videoRef} autoPlay muted style={{ width: '100%', height: '100%' }} />
<canvas ref={canvasRef} style={{ position: 'absolute', top: 0, left: 0, pointerEvents: 'none' }} />
</div>
);
};
export default VideoWithDots;
Editor is loading...
Leave a Comment