# Camera (/docs/camera)





`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.

```tsx
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.

<Callout title="Every demo here waits for a click">
  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.
</Callout>

## Playground [#playground]

<story.Playground />

### Full prop browser [#full-prop-browser]

<story.WithControl />

## Basic [#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.

<Preview code="`<Camera onCapture={(file) => setPhoto(file)} />`">
  <BasicDemo />
</Preview>

## Capture [#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](/docs/image-cropper), which takes the `File` as its `src`.

<Preview code="&#x22;const [photo, setPhoto] = useState<File | null>(null);\nconst url = useObjectUrl(photo);\n\n<Camera onCapture={setPhoto} />\n{url && <Image src={url} alt=\&#x22;The photo you took\&#x22; />}&#x22;">
  <CaptureDemo />
</Preview>

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 [#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:

<Preview code="&#x22;const camera = useCamera({ facing: 'user', ratio: '1/1' });\n\n<Camera.Root camera={camera} onCapture={setPhoto}>\n  <Camera.Viewfinder radius=\&#x22;md\&#x22;>\n    <Camera.Guide shape=\&#x22;circle\&#x22; size={0.75} />\n    <Camera.Live className=\&#x22;absolute start-2 top-2\&#x22; />\n    <Camera.Status />\n  </Camera.Viewfinder>\n  <div className=\&#x22;grid grid-cols-[1fr_auto_1fr] items-center gap-3\&#x22;>\n    <Camera.Devices />\n    <Camera.Shutter />\n    <Camera.Flip className=\&#x22;justify-self-end\&#x22; />\n  </div>\n</Camera.Root>&#x22;">
  <ComposedDemo />
</Preview>

`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](/docs/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 [#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:

<Preview code="&#x22;const camera = useCamera({\n  facing: 'environment',\n  ratio: '3/4',\n  resolution: { width: 3840, height: 2160 },\n});\n\n<Camera.Root camera={camera} color=\&#x22;green\&#x22;>\n  <Camera.Viewfinder>\n    <Camera.Guide shape=\&#x22;rectangle\&#x22; ratio=\&#x22;210/297\&#x22; size={0.85} />\n    <Camera.Status />\n  </Camera.Viewfinder>\n  <Camera.Shutter />\n  <Camera.Flip />\n</Camera.Root>&#x22;">
  <DocumentDemo />
</Preview>

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 [#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:

<Preview code="&#x22;<Camera onCapture={setPhoto}>\n  {() => (\n    <Button asChild variant=\&#x22;light\&#x22; startSlot={<FileImage />}>\n      <label>\n        Choose a file\n        <input type=\&#x22;file\&#x22; accept=\&#x22;image/*\&#x22; className=\&#x22;sr-only\&#x22; onChange={pick} />\n      </label>\n    </Button>\n  )}\n</Camera>&#x22;">
  <FileAlternativeDemo />
</Preview>

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 [#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 [#usecamera]

```tsx
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`, and `next`, where `flip()` 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 from `devices`.
* `capture({ type, quality, mirror })` resolves the `File`, and turns the camera off.
* `props` goes 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](/docs/photo-capture) 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 [#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 `File` is yours to send, or not.
* **No storage.** The chosen camera lives in the hook's state, not in `localStorage`.

## Accessibility [#accessibility]

* **The shutter is a native button** named "Take photo", so <kbd>Space</kbd> and <kbd>Enter</kbd> 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-slow` token. Under `prefers-reduced-motion` there'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 [#internationalization]

Every string is in `translations`. Anything with a number is a function, given the number already formatted for the locale from [`IntlProvider`](/docs/intl). 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.

<Preview code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <Camera shape=\&#x22;circle\&#x22; translations={arabic} />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

| 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]

`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.

```tsx
<Camera icons={{ shutter: <Aperture className={iconStroke} />, flip: <RefreshCw className={iconStroke} /> }} />
```

## Browser support [#browser-support]

* **A secure context.** `getUserMedia` only exists on `https:` and `localhost`. On `http:` the status is `unsupported`.
* **Iframes need `allow="camera"`.** A page embedded without it can't ask: `<iframe src="…" allow="camera">`. Its status is `unsupported` or `denied`, depending on the browser.
* **iOS needs `playsinline`**, or the video opens full screen. The viewfinder sets it, with `muted` and `autoplay`, and also calls `play()`, 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 [#api]

<TypeTable
  type="{
  facing: {
    type: '&#x22;user&#x22; | &#x22;environment&#x22;',
    default: '&#x22;user&#x22;',
    description: &#x22;The camera to open first: the front one, or the back one.&#x22;,
  },
  device: { type: &#x22;string&#x22;, description: &#x22;A deviceId to open first. Wins over facing.&#x22; },
  ratio: {
    type: 'number | &#x22;w/h&#x22;',
    description: &#x22;The frame shape to ask for, and the viewfinder's box. 4/3 when unset.&#x22;,
  },
  resolution: {
    type: &#x22;{ width: number; height: number }&#x22;,
    default: &#x22;1920 × 1080&#x22;,
    description: &#x22;The capture size to aim for. Ideal, never exact.&#x22;,
  },
  lazy: {
    type: &#x22;boolean&#x22;,
    default: &#x22;false&#x22;,
    description: &#x22;Waits for start() even when the camera is already allowed, instead of turning it on as it mounts.&#x22;,
  },
  onCapture: { type: &#x22;(file: File) => void&#x22;, description: &#x22;Receives the photo. The camera is already off.&#x22; },
  output: {
    type: &#x22;{ type?: string; quality?: number }&#x22;,
    default: '{ type: &#x22;image/jpeg&#x22;, quality: 0.9 }',
    description: &#x22;The photo's encoding.&#x22;,
  },
  mirror: { type: &#x22;boolean&#x22;, default: &#x22;false&#x22;, description: &#x22;Saves the photo mirrored, as the selfie preview shows it.&#x22; },
  shape: { type: '&#x22;circle&#x22; | &#x22;rectangle&#x22;', description: &#x22;A framing guide over the picture. None when unset.&#x22; },
  radius: {
    type: '&#x22;none&#x22; | &#x22;xs&#x22; | &#x22;sm&#x22; | &#x22;md&#x22; | &#x22;lg&#x22; | &#x22;xl&#x22; | &#x22;full&#x22;',
    default: '&#x22;xs&#x22;',
    description: &#x22;The viewfinder's corners, from the media scale.&#x22;,
  },
  color: {
    type: &#x22;Color&#x22;,
    default: '&#x22;brand&#x22;',
    description: &#x22;The palette of the shutter, the guide's edge and the panels' buttons.&#x22;,
  },
  translations: { type: &#x22;CameraTranslations&#x22;, description: &#x22;See Internationalization.&#x22; },
  icons: { type: &#x22;CameraIcons&#x22;, description: &#x22;See Icons.&#x22; },
  classNames: {
    type: &#x22;{ viewfinder?, video?, guide?, status?, controls?, shutter?, flip? }&#x22;,
    description: &#x22;Per-part classes.&#x22;,
  },
  children: {
    type: &#x22;(status: CameraStatus) => ReactNode&#x22;,
    description: &#x22;Rendered in every status panel: a file alternative.&#x22;,
  },
  testId: { type: &#x22;string&#x22;, description: &#x22;Renders as data-testid on the root. See [Testing](/docs/testing).&#x22; },
}"
/>

`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 [#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 [#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`.

```tsx
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.
