Skip to content

Commit a938251

Browse files
committed
feat(webcam): canvas의 크기를 비디오 사이즈로 조정
1 parent 5f0725f commit a938251

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

src/hooks/useWebcam.tsx

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { MutableRefObject, RefObject, useEffect, useRef, useState } from 'react'
22

3+
// 프레임을 이미지로 저장하는 함수
34
export const captureFrame = (
45
animationIdRef: MutableRefObject<number | undefined>,
56
videoRef: RefObject<HTMLVideoElement>,
@@ -17,11 +18,28 @@ export const captureFrame = (
1718
}
1819

1920
// 브라우저에 비디오 화면을 그리는 함수
20-
const startVideo = async (videoRef: RefObject<HTMLVideoElement>) => {
21+
const startVideo = async (
22+
videoRef: RefObject<HTMLVideoElement>,
23+
canvasRef: RefObject<HTMLCanvasElement>,
24+
) => {
2125
const stream = await navigator.mediaDevices.getUserMedia({ video: true })
2226
if (!videoRef || !videoRef.current || videoRef.current.srcObject) return
2327
videoRef.current.srcObject = stream
2428
videoRef.current.play()
29+
30+
setCanvas(videoRef, canvasRef)
31+
}
32+
33+
// 비디오의 크기에 따른 Canvas의 크기를 설정하는 함수
34+
const setCanvas = (
35+
videoRef: RefObject<HTMLVideoElement>,
36+
canvasRef: RefObject<HTMLCanvasElement>,
37+
) => {
38+
videoRef.current?.addEventListener('loadedmetadata', () => {
39+
if (!canvasRef.current || !videoRef.current) return
40+
canvasRef.current.width = videoRef.current.videoWidth
41+
canvasRef.current.height = videoRef.current.videoHeight
42+
})
2543
}
2644

2745
const useWebcam = (videoRef: RefObject<HTMLVideoElement>) => {
@@ -30,7 +48,7 @@ const useWebcam = (videoRef: RefObject<HTMLVideoElement>) => {
3048
const [isCapturing, setIsCapturing] = useState(false)
3149

3250
useEffect(() => {
33-
startVideo(videoRef)
51+
startVideo(videoRef, canvasRef)
3452

3553
if (isCapturing) {
3654
animationFrameId.current = captureFrame(

0 commit comments

Comments
 (0)