Camera
Take a photo in the page. A live viewfinder with a framing guide, a shutter, a camera switch, and a panel for every state, from the first permission prompt to the steps that undo a refusal. The photo comes back as a File.
Camera shows the camera's live picture and takes a photo of it. Before the browser's permission prompt it explains why it's asking; after a refusal it lists the steps to undo it in the browser the visitor is using. Press the shutter and onCapture receives a File: the full frame at the camera's own resolution, with no EXIF. The camera turns off as soon as the photo is taken, and nothing leaves the page.
import { Camera } from '@42-central/ui-react/camera';
<Camera facing="user" shape="circle" onCapture={(file) => setPhoto(file)} />The parts run on useCamera, a headless hook from the same entry, which you can use without them.
Once you've allowed the camera for this site, useCamera turns it on as soon as it mounts, with no priming screen. So that six demos don't turn your camera on as the page loads, each one starts behind a button.
Playground
Component
Dir
Presets
Props
Code
<Component facing="user" />Full prop browser
Basic
The first time, the camera explains itself and waits for Enable camera, which brings up the browser's prompt. Once it's allowed, the picture appears, mirrored like a mirror for the front camera, with a Camera on badge. The switch shows when there's more than one camera.
Code
<Camera onCapture={(file) => setPhoto(file)} />Capture
onCapture gets a File named and typed for what the browser encoded: image/jpeg at a 0.9 quality by default, set with output={{ type, quality }}. It is the camera's whole frame at its own resolution, not the part the viewfinder shows: the viewfinder covers its box and crops what overflows, the photo doesn't. Crop it with ImageCropper, which takes the File as its src.
Code
const [photo, setPhoto] = useState<File | null>(null);
const url = useObjectUrl(photo);
<Camera onCapture={setPhoto} />
{url && <Image src={url} alt="The photo you took" />}A selfie is saved the right way round, as others see you, even though the preview is mirrored. Pass mirror to save it as the preview shows it. A browser that can't encode the type you ask for (Safari has no WebP encoder) falls back to PNG, and the File's type and extension say so.
Composable parts
<Camera> is one arrangement of the parts. Compose your own around a useCamera() of your own, here a square box with a face guide and the camera picker:
Code
const camera = useCamera({ facing: 'user', ratio: '1/1' });
<Camera.Root camera={camera} onCapture={setPhoto}>
<Camera.Viewfinder radius="md">
<Camera.Guide shape="circle" size={0.75} />
<Camera.Live className="absolute start-2 top-2" />
<Camera.Status />
</Camera.Viewfinder>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3">
<Camera.Devices />
<Camera.Shutter />
<Camera.Flip className="justify-self-end" />
</div>
</Camera.Root>Camera.Guide dims the picture around a hole: a circle for a face, a rectangle for a card or a page. It's the same dim as ImageCropper's, so a photo framed here crops the same way there. size is the hole's share of the viewfinder along its tighter side, and a rectangle takes a ratio.
Camera.Devices is a Select of the cameras by name. It shows once the camera is allowed, since browsers hide the names until then, and only when there's more than one. The choice lasts as long as the hook: nothing is stored.
Document mode
The back camera, a portrait box, a guide shaped like an A4 page, and a 4K request, for a document that has to be readable:
Code
const camera = useCamera({
facing: 'environment',
ratio: '3/4',
resolution: { width: 3840, height: 2160 },
});
<Camera.Root camera={camera} color="green">
<Camera.Viewfinder>
<Camera.Guide shape="rectangle" ratio="210/297" size={0.85} />
<Camera.Status />
</Camera.Viewfinder>
<Camera.Shutter />
<Camera.Flip />
</Camera.Root>Every constraint on the picture is an ideal, never an exact: a camera that can't do 4K opens at the closest size it has rather than failing, and a laptop without a back camera opens its webcam. The one exact is a camera picked by device, select() or flip(): as an ideal, Chrome can trade it for a better resolution match and reopen the same camera. If that camera is gone, the hook retries with any.
A file alternative
Some visitors won't be able to use the camera: they refused it, the page is in an iframe without permission, the camera is busy. Camera.Status's children, a function of the status, render in every panel, so a way through is always there:
Code
<Camera onCapture={setPhoto}>
{() => (
<Button asChild variant="light" startSlot={<FileImage />}>
<label>
Choose a file
<input type="file" accept="image/*" className="sr-only" onChange={pick} />
</label>
</Button>
)}
</Camera>To replace a panel entirely, read the status yourself: useCameraContext() returns the camera, the translations and the icons for any part of your own inside Camera.Root.
States
useCamera().status, and the panel Camera.Status shows for it:
| Status | When | Panel |
|---|---|---|
idle | On the server, and after stop() or a photo. | "The camera is off", Turn on camera. Nothing before the client has checked. |
prompt | Ready to ask, the browser hasn't been asked yet. | Why the browser is about to ask, Enable camera. |
starting | Asked, waiting for the first frame. | "Starting the camera…", over a skeleton. |
live | Frames are showing. | None. |
paused | The page was hidden, or another app took the camera. | Tap to resume. |
denied | The visitor, or a site setting, refused the camera. | The steps to allow it, for this browser. |
blocked | The operating system refused it to the browser. | The steps to allow it, for this system. |
busy | Another app or tab holds the camera. | Try again. |
missing | No camera. | Try again. |
unsupported | No camera API: an http: page, an old browser, an iframe without allow="camera", a browser that can't show a prompt here. | An explanation, no button. |
error | Anything else, including a camera with no frame after 8 seconds. | Try again. |
The recovery steps are for Chrome on a desktop, Chrome on Android, Safari on macOS, Safari on iOS (every iOS browser shares its permissions) and Firefox, with generic steps for anything else. The browser is read from its user agent, conservatively: when in doubt, the generic steps.
useCamera
const camera = useCamera({ facing: 'environment', ratio: '4/3' });
<video {...camera.props} />
<button onClick={async () => upload(await camera.capture())}>Take photo</button>It returns plain state and handlers:
status,permission(the hint),facing,device,devices,capabilities, andnext, whereflip()would go.start()asks for the camera, and also resumes and retries.stop()turns it off.flip()switches to the camera facing the other way, or to the next webcam.select(deviceId)switches to one fromdevices.capture({ type, quality, mirror })resolves theFile, and turns the camera off.propsgoes on your<video>: it carries the ref,autoPlay,muted,playsInline, and the events that tell the hook the first frame has arrived.
Once the camera is allowed, the hook turns it on as it mounts. Pass lazy to keep it off until start(), for a camera that sits behind a choice and mustn't light up before it: PhotoCapture mounts its camera lazily, and starts it when you pick Take photo.
The hook reads navigator only in effects, so it renders idle on the server. navigator.permissions is a hint and nothing more: Safari keeps reporting prompt after a refusal, so the real answer is whatever getUserMedia says.
Privacy
- The light is on only while the picture is. The camera stops after a photo, on
stop(), when the page is hidden or closed, and when the component unmounts. A stream that arrives after any of those is stopped as it arrives. - One camera at a time. The current one is stopped before the next is asked for.
- No EXIF. The photo is drawn from the video onto a canvas: no location, no device, no date.
- No network. The kit never uploads anything. The
Fileis yours to send, or not. - No storage. The chosen camera lives in the hook's state, not in
localStorage.
Accessibility
- The shutter is a native button named "Take photo", so Space and Enter take the photo. It's disabled until the camera is live.
- Focus is yours to move. After a photo the camera is off and the shutter disabled. Move focus to whatever comes next, a "Use photo" button or the preview, and back to the shutter on a retake.
- A polite live region announces "Starting the camera", "Camera ready", "Camera paused" and "Photo taken". Failure panels are
role="alert". - The switch names its destination: "Switch to back camera" from the front one.
- The guide and the flash are decorative (
aria-hidden). In forced colors the guide's dim steps aside and only its edge is drawn. - Reduced motion. The shutter flashes white for a moment on the
--duration-slowtoken. Underprefers-reduced-motionthere's no fade: the frame is outlined for the same moment, then not. - The video is named "Camera preview".
- Touch targets are 44px or more: the switch is 44px, the shutter 64px.
Internationalization
Every string is in translations. Anything with a number is a function, given the number already formatted for the locale from IntlProvider. The layout uses logical properties throughout, so under a right-to-left locale the badge sits at the inline start and the panels read right to left. The video itself isn't flipped for direction; only the front camera is mirrored.
Code
<IntlProvider locale="ar-EG">
<div dir="rtl" lang="ar">
<Camera shape="circle" translations={arabic} />
</div>
</IntlProvider>| Key | Default |
|---|---|
viewfinder | "Camera preview" |
primeTitle | "Take a photo with your camera" |
primeBody | "Your browser will ask to use the camera. It's only on while you take the photo, and nothing is uploaded until you choose to." |
enable | "Enable camera" |
offTitle | "The camera is off" |
start | "Turn on camera" |
starting | "Starting the camera…" |
pausedTitle | "The camera is paused" |
resume | "Tap to resume" |
busyTitle / busyBody | "The camera is in use" / "Another app or tab is using it. Close it, then try again." |
missingTitle / missingBody | "No camera found" / "Connect a camera, or check that it's turned on, then try again." |
unsupportedTitle / unsupportedBody | "The camera isn't available here" / "This browser can't use the camera on this page." |
errorTitle / errorBody | "The camera couldn't start" / "Something went wrong while starting it." |
retry | "Try again" |
deniedTitle / deniedBody | "Camera access is blocked" / "To take a photo, allow the camera for this site:" |
deniedSteps | (browser) => string[], for chrome-desktop, chrome-android, safari-macos, safari-ios, firefox and other |
blockedTitle / blockedBody | "Your system is blocking the camera" / "Your browser isn't allowed to use the camera. To allow it:" |
blockedSteps | (os) => string[], for macos, windows, android, ios and other |
shutter | "Take photo" |
flip | (facing) => "Switch to back camera", "Switch to front camera", or "Switch camera" when facing is null |
devices | "Camera" |
device | (index) => `Camera ${index}` , for a camera with no name |
live | "Camera on" |
announceStarting / announceReady / announcePaused / announceTaken | "Starting the camera" / "Camera ready" / "Camera paused" / "Photo taken" |
Icons
icons replaces any of the defaults, per slot: shutter, flip, start (the buttons that turn the camera on), retry, and off (over a failure panel). Your icons are drawn as given: add className={iconStroke} (from @42/ui-react) for the kit's 1.5px line.
<Camera icons={{ shutter: <Aperture className={iconStroke} />, flip: <RefreshCw className={iconStroke} /> }} />Browser support
- A secure context.
getUserMediaonly exists onhttps:andlocalhost. Onhttp:the status isunsupported. - Iframes need
allow="camera". A page embedded without it can't ask:<iframe src="…" allow="camera">. Its status isunsupportedordenied, depending on the browser. - iOS needs
playsinline, or the video opens full screen. The viewfinder sets it, withmutedandautoplay, and also callsplay(), which Safari needs to start a stream. - Permission hints. Chrome and Firefox report a granted camera, so the priming screen is skipped. Safari always reports
prompt, so it always primes.
Deferred for now: Chrome's <usermedia> element, which would let a refused camera be re-allowed in one click; torch and zoom, which capabilities already reports where the browser does; and ImageCapture.takePhoto(), for full-sensor stills on the browsers that have it.
API
Prop
Type
Camera.Root takes camera (a useCamera() result) instead of facing, device, ratio, resolution and lazy, and its own children; the rest is the same.
Parts
| Part | Renders | Notes |
|---|---|---|
Camera.Root | <div> | The camera, translations, icons, color, onCapture. The polite live region. Takes asChild. |
Camera.Viewfinder | <div> around a <video> | The ratio box the video covers. ratio, radius, classNames.video. Its children sit over the picture. |
Camera.Guide | <div aria-hidden> | shape, size (0–1), ratio for a rectangle. While live. |
Camera.Shutter | <button> | Takes the photo. Takes asChild and a ref, to move focus back to it. |
Camera.Flip | <button> | With two cameras or more. |
Camera.Devices | A Select | With two cameras or more, once allowed. |
Camera.Status | <div> | One panel per status. children(status) in each. |
Camera.Live | A Badge | "Camera on", while live. |
Testing
testId lands on the root. jsdom has no camera, so give it a fake navigator.mediaDevices whose getUserMedia resolves an object with getTracks() and getVideoTracks(), and whose tracks have stop(), getSettings() and addEventListener. The status stays starting until the video's first frame: give the <video> (found by its label, "Camera preview") a videoWidth and fire loadeddata. jsdom has no canvas either, so stub HTMLCanvasElement.prototype.getContext and toBlob to test onCapture.
Object.defineProperty(navigator, 'mediaDevices', { configurable: true, value: fakeMedia });
render(<Camera onCapture={onCapture} />);
await user.click(screen.getByRole('button', { name: 'Enable camera' }));
const video = screen.getByLabelText('Camera preview');
Object.defineProperty(video, 'videoWidth', { value: 1280 });
fireEvent.loadedData(video);
await user.click(screen.getByRole('button', { name: 'Take photo' }));In a real browser, Chromium's --use-fake-device-for-media-stream and --use-fake-ui-for-media-stream flags give Playwright a camera that's always allowed.
Changelog
- #464
No computed-style read on mount in production: the RTL direction check runs in development only
- #359
New
Cameraparts and headlessuseCamera():Viewfinder,Guide(circle or document cut-out),Shutter,Flip,DevicesandStatuscover denied, blocked, busy and missing cameras with per-browser recovery steps;onCapturehands you aFile
ImageCropper
Pick the part of an image to keep. Drag and resize the selection, zoom, rotate and flip the image, then export the crop as a Blob or as coordinates for your server.
PhotoCapture
Take a photo with the camera or pick a file, crop it, and get a File back. A composition of Camera, FileTrigger and ImageCropper, driven by a small step reducer.