Enable camera access in an iframe
masterIf you are embedding your camera application within an <iframe>, you must explicitly allow camera access using the allow attribute.
<iframe src="https://example.com/camera-pro-iframe" allow="camera;"/>repository·master·Indexed 42 days ago
https://github.com/purple-technology/react-camera-proA universal, mobile-friendly camera component for React version 1.4.0, designed for Android, iOS, and standard webcams. It provides a high-level API via refs for taking photos, switching between 'user' and 'environment' facing modes, and toggling the torch. Features include configurable aspect ratios, custom error messages, and callbacks for video readiness and camera count.
If you are embedding your camera application within an <iframe>, you must explicitly allow camera access using the allow attribute.
<iframe src="https://example.com/camera-pro-iframe" allow="camera;"/>The react-camera-pro-example project is bootstrapped with Create React App. You can manage the development, testing, and production build processes using the following npm scripts in the project directory:
# Run the app in development mode at http://localhost:3000
npm start
# Launch the test runner in interactive watch mode
npm test
# Build the app for production in the `build` folder
npm run build
# Remove the single build dependency and copy all configuration files (one-way operation)
npm run ejectTo use the universal camera component in your React project, install the package using npm:
npm install --save react-camera-proUse the facingMode prop to select the camera and aspectRatio to define the video dimensions.
// Use the environment (rear) camera
const Cam = () => <Camera ref={camera} facingMode='environment' />
// Set a specific aspect ratio
const Cam = () => <Camera ref={camera} aspectRatio={16 / 9} />The Camera component is controlled via a React ref. You can use the ref to access public methods like takePhoto(). Note that WebRTC requires a secure connection (HTTPS), though localhost is supported for testing in Chrome (Safari may not support localhost testing).
import React, { useState, useRef } from "react";
import {Camera} from "react-camera-pro";
const Component = () => {
const camera = useRef(null);
const [image, setImage] = useState(null);
return (
<div>
<Camera ref={camera} />
<button onClick={() => setImage(camera.current.takePhoto())}>Take photo</button>
{image && <img src={image} alt='Taken photo'/>}
</div>
);
}
export default Component;When you attach a ref to the Camera component, you gain access to the following public methods:
takePhoto(): string: Captures a photo and returns it as a base64 encoded JPEG string. The photo maintains the view's aspect ratio and uses FullHD resolution (or the maximum supported by the hardware).switchCamera(): 'user' | 'environment': Toggles between the front and rear cameras. Returns the new active facingMode.getNumberOfCameras(): number: Returns the total number of available video input devices.The Camera component accepts several props to control its behavior and appearance:
facingMode: Sets the default camera. Can be 'user' (front-facing, mirrored) or 'environment' (rear-facing, not mirrored). Default is 'user'.aspectRatio: Defines the video aspect ratio. Can be 'cover' (to fill the container) or a number (e.g., 16 / 9, 4 / 3). Default is 'cover'.numberOfCamerasCallback: A callback function (numberOfCameras: number) => void that is triggered when the number of available cameras changes.errorMessages: An optional object to override default error messages.You can provide a custom errorMessages object to the Camera component to change the text displayed when errors occur. The object supports the following keys:
noCameraAccessible: When no camera device is found.permissionDenied: When the user denies camera permissions.switchCamera: When attempting to switch cameras on a device with only one camera.canvas: When the browser does not support canvas.errorMessages: {
noCameraAccessible?: string;
permissionDenied?: string;
switchCamera?: string;
canvas?: string;
};The Camera component exposes a set of imperative methods through a ref. These methods allow you to interact with the camera hardware and capture images directly.
Available methods and properties:
takePhoto(type?: 'base64url' | 'imgData'): Captures a photo. Returns a string (if type is 'base64url') or ImageData (if type is 'imgData').switchCamera(): Toggles between the available facing modes. Returns the new FacingMode ('user' or 'environment').getNumberOfCameras(): Returns the total number of cameras detected.toggleTorch(): Toggles the device's flashlight/torch. Returns a boolean indicating the new state.torchSupported: A boolean property indicating if the current device supports a torch.import { useRef } from 'react';
import { Camera } from 'react-camera-pro';
// Note: The type of the ref is CameraType
const cameraRef = useRef<any>(null);
const handleCapture = () => {
if (cameraRef.current) {
const photo = cameraRef.current.takePhoto('base64url');
console.log(photo); // string
}
};
const handleSwitch = () => {
if (cameraRef.current) {
const newMode = cameraRef.current.switchCamera();
console.log("New mode:", newMode);
}
};
<Camera ref={cameraRef} />The Camera component accepts several props to control its behavior, camera selection, and error messaging.
Key props include:
facingMode: Specifies whether to use the 'user' (front) or 'environment' (back) camera.aspectRatio: Sets the video aspect ratio. Can be 'cover' or a numeric ratio like 16/9 or 4/3.videoSourceDeviceId: A specific device ID to use for the video source.errorMessages: An object containing custom strings for different error states:noCameraAccessiblepermissionDeniedswitchCameracanvasvideoReadyCallback: A function called when the video stream is ready.numberOfCamerasCallback: A function called with the total number of available cameras.<Camera
facingMode="environment"
aspectRatio={16/9}
errorMessages={{
noCameraAccessible: "No camera found",
permissionDenied: "Please allow camera access",
switchCamera: "Could not switch camera",
canvas: "Canvas error"
}}
videoReadyCallback={() => console.log("Camera is ready!")}
/>The Camera component exposes an imperative API via ref. You can use this ref to trigger actions like taking photos, switching cameras, or toggling the flashlight.
takePhoto(type?: 'base64url' | 'imgData'): Captures a frame from the current video stream.type is 'imgData', it returns an ImageData object.type is 'base64url' (or omitted), it returns a Base64 encoded JPEG data URL.switchCamera(): Toggles between the 'user' and 'environment' facing modes. Returns the new FacingMode.getNumberOfCameras(): Returns the current number of available video input devices.toggleTorch(): Toggles the camera's flashlight (torch) on or off. Returns the new boolean state.torchSupported: A boolean property on the ref indicating if the current device/stream supports the torch feature.import { useRef } from 'react';
import { Camera } from 'react-camera-pro';
// Note: The ref type is 'unknown' in the source,
// but you can cast it to access the methods below.
const cameraRef = useRef<any>(null);
const handleCapture = () => {
const photo = cameraRef.current.takePhoto('base64url');
console.log(photo);
};
const handleSwitch = () => {
cameraRef.current.switchCamera();
};
const handleTorch = () => {
if (cameraRef.current.torchSupported) {
cameraRef.current.toggleTorch();
}
};
return (
<Camera ref={cameraRef} />
);The Camera component accepts several props to control its behavior, appearance, and callbacks.
facingMode: Sets the preferred camera direction. Defaults to 'user'. Valid values are typically 'user' or 'environment'.aspectRatio: Controls how the camera view fills its container. Defaults to 'cover'.videoSourceDeviceId: An optional specific device ID to use for the video stream.numberOfCamerasCallback: A callback function that receives the total number of available video input devices whenever it changes.videoReadyCallback: A callback function triggered when the video stream has successfully loaded data.errorMessages: An object allowing you to override default error strings for:noCameraAccessiblepermissionDeniedswitchCameracanvas<Camera
facingMode="environment"
aspectRatio="contain"
numberOfCamerasCallback={(count) => console.log(count)}
videoReadyCallback={() => console.log('Video is ready!')}
/>