react网络摄像头的问题



我的react网络摄像头有一个问题,当我立即打开页面时,它会请求我打开相机的权限,但我需要的是只有当我按下按钮拍摄时才请求我的权限

const WebcamCapture = () => {
const webcamRef = React.useRef(null)
const [imgSrc, setImgSrc] = React.useState(null)
const capture = React.useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot()
setImgSrc(imageSrc)
}, [webcamRef, setImgSrc])
return (
<div>
<div className="w-full bg-dark-20 flex justify-center items-center relative ">
<AiOutlineCamera className="text-6xl py-60 h-auto absolute m-auto" />
<Webcam
className="w-full h-64"
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
/>
</div>
<div className="flex justify-end mt-5">
<button
className="text-xs flex justify-center items-center px-4 py-2 border-2  border-dark-80 rounded"
onClick={capture}>
Usar Camara web <BiWebcam className="ml-2 text-base" />
</button>
</div>
{imgSrc && <img src={imgSrc} />}
</div>
)
}
export default WebcamCapture

在应用程序中,WebcamCapture装载时会加载Webcam组件。当Webcam加载时,它将请求permission。如果要在用户按下按钮之前不加载Webcam组件,则需要根据由按钮控制的状态变量有条件地渲染Webcam。例如,有一个按钮,一旦按下,就会渲染网络摄像头和拍照按钮:

const WebcamCapture = () => {
const webcamRef = React.useRef(null)
const [camOpen, setCamOpen] = React.useState(false)
const [imgSrc, setImgSrc] = React.useState(null)

const capture = React.useCallback(() => {
if (webcamRef){
const imageSrc = webcamRef.current.getScreenshot()
setImgSrc(imageSrc)
}
}, [webcamRef, setImgSrc, webcamRef])
return (
<div>
{camOpen && 
<>
<div className="...">
<Webcam/>
</div>
<div className="flex justify-end mt-5">
<button
className="..."
onClick={capture}>
Usar Camara web <BiWebcam className="ml-2 text-base" />
</button>
</div>
</>
}
<button onClick={capture}>Open the camera</button>
{imgSrc && <img src={imgSrc} />}
</div>
)
}
export default WebcamCapture

但你不能让Webcam已经在使用,然后只在用户想拍照时才申请使用许可。您可以创建一个自定义模态,该模态表示类似";你确定要拍照吗"一旦用户单击按钮捕捉照片,但为了让网络摄像头呈现,它首先需要获得许可。

最新更新