let overlay, ctx; let ORIGINAL_ASPECT = ORIGINAL_WIDTH / ORIGINAL_HEIGHT; function initOverlay({ canvasId = 'overlayCanvas', videoContainerSelector = '.cam-container', width, height }) { overlay = document.getElementById(canvasId); ctx = overlay.getContext('2d'); if (width && height) { ORIGINAL_WIDTH = width; ORIGINAL_HEIGHT = height; ORIGINAL_ASPECT = width / height; } const resizeCanvasToVideo = () => { const camContainer = document.querySelector(videoContainerSelector); const video = camContainer.querySelector('video'); if (!video || !overlay) return; const rect = camContainer.getBoundingClientRect(); const containerWidth = rect.width; const containerHeight = rect.height; const containerAspect = containerWidth / containerHeight; let displayWidth, displayHeight; if (containerAspect > ORIGINAL_ASPECT) { displayHeight = containerHeight; displayWidth = displayHeight * ORIGINAL_ASPECT; } else { displayWidth = containerWidth; displayHeight = displayWidth / ORIGINAL_ASPECT; } const offsetX = (containerWidth - displayWidth) / 2; const offsetY = (containerHeight - displayHeight) / 2; overlay.width = ORIGINAL_WIDTH; overlay.height = ORIGINAL_HEIGHT; overlay.style.width = `${displayWidth}px`; overlay.style.height = `${displayHeight}px`; overlay.style.left = `${offsetX}px`; overlay.style.top = `${offsetY}px`; }; window.addEventListener('resize', resizeCanvasToVideo); resizeCanvasToVideo(); } function clearOverlay() { if (ctx && overlay) { ctx.clearRect(0, 0, overlay.width, overlay.height); } } function drawObjects(objects = []) { if (!ctx || !overlay) return; const scaleX = overlay.width / ORIGINAL_WIDTH; const scaleY = overlay.height / ORIGINAL_HEIGHT; objects.forEach(obj => { const color = obj.type === 1 ? 'red' : 'lime'; const x = obj.coordinates[0] * scaleX; const y = obj.coordinates[1] * scaleY; const w = obj.width * scaleX; const h = obj.height * scaleY; ctx.strokeStyle = color; ctx.lineWidth = 5; ctx.strokeRect(x, y, w, h); }); }