camera-torch
v0.1.0
Published
Torch, zoom, focus and exposure control for a live web camera stream. No Cordova, no Capacitor - just the browser's own MediaStreamTrack API, done right.
Maintainers
Readme
camera-torch
Turn the phone's flashlight on from a web page. Plus zoom, focus and exposure — on the camera stream you already have.
Every other torch package on npm is Cordova, Capacitor or React Native. The browser has been able to do this on its own for years — it is just that nothing about the API tells you how.
// Before — looks reasonable, does nothing at all
await track.applyConstraints({ torch: true }); // silently ignored
await navigator.mediaDevices.getUserMedia({ video: { torch: true } }); // throws
// After
const cam = attach(stream);
if (cam.can.torch) await cam.torch(true); // the LED comes onWhy this exists
Torch control is four lines of platform API with five ways to get it wrong. This package is those five things:
- Torch only listens inside the
advancedarray.applyConstraints({ torch: true })resolves successfully and does nothing —torchis not a standard constraint, so the basic constraint set is allowed to drop it on the floor. It has to beapplyConstraints({ advanced: [{ torch: true }] }), and it can never be part of the originalgetUserMedia()call (that throwsTypeError). This is the number-one reason people conclude the web cannot do torch. getCapabilities()does not always exist. It is absent in Firefox and in a fair number of older Android WebViews, and on some devices it exists but returns{}until the camera has settled.readCapabilities()always hands back a fully-formed object with everything absent, so you branch on data instead of ontypeof.- The torch survives the track. Stop a track with
torch: truestill applied and the LED stays physically lit on many Android devices until something else claims the camera — including after the page is closed.detach()writestorch: falsebefore letting go, and theendedevent is watched so state never lies. See Gotchas; this is the bug your users will report. - Torch needs a live, environment-facing track. A stopped track, an audio track, or a front
camera each fail differently and unhelpfully. Here they are
'not-live','not-video'and'unsupported-capability'before anything reaches the device. - Zoom has a device-specific range and a step. Ask for
zoom: 3on a camera that reports{ min: 1, max: 2.4, step: 0.1 }and you get anOverconstrainedError.zoom()clamps into the real range, snaps to the real step grid (measured frommin, not from zero), and resolves with the value it actually applied. OverconstrainedErrorknows which constraint it rejected — inerr.constraint— and nobody ever reads it. Here it becomes aCameraErrorwithcode: 'out-of-range'and that constraint name attached.
Install
npm install camera-torchOr straight from a CDN — the IIFE build exposes the global CameraTorch:
<script src="https://unpkg.com/camera-torch"></script>
<script>
const cam = CameraTorch.attach(stream);
if (cam.can.torch) cam.torch(true);
</script>No runtime dependencies. React is an optional peer dependency, used only by camera-torch/react.
Quick start
import { attach, isSupported } from 'camera-torch';
if (!isSupported()) {
// Firefox, or an insecure origin. Render your scanner without a torch button.
}
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' }, // the front camera never has a torch
});
document.querySelector('video').srcObject = stream;
const cam = attach(stream);
console.log(cam.can); // { torch: true, zoom: true, focus: true, exposure: false }
console.log(cam.ranges); // { zoom: { min: 1, max: 8, step: 0.1 } }
const button = document.querySelector('#torch');
button.hidden = !cam.can.torch;
button.onclick = async () => {
const on = await cam.toggleTorch();
button.textContent = on ? 'Torch off' : 'Torch on';
};
// When you are done — this order matters.
cam.detach(); // torch off first
stream.getTracks().forEach((t) => t.stop()); // then release the cameraattach() also takes a bare MediaStreamTrack, and attaching twice to the same track hands back
the same control object, so it is safe to call from a re-render.
React
import { useCameraTorch } from 'camera-torch/react';
function Scanner({ stream }) {
const { can, ranges, torchOn, toggleTorch, zoom, error } = useCameraTorch(stream);
return (
<>
{can.torch && (
<button onClick={() => toggleTorch().catch(() => {})}>
{torchOn ? 'Torch off' : 'Torch on'}
</button>
)}
{ranges.zoom && (
<input
type="range"
min={ranges.zoom.min}
max={ranges.zoom.max}
step={ranges.zoom.step || 0.1}
defaultValue={ranges.zoom.min}
onChange={(e) => zoom(Number(e.target.value)).catch(() => {})}
/>
)}
{error && <p role="alert">{error.message}</p>}
</>
);
}The hook re-attaches when source changes and detaches on unmount — and because detaching turns
the torch off, unmounting the component cannot leave the LED lit. Pass null while you have no
stream yet. It is SSR-safe: nothing touches the camera during render.
API
Functions
| Function | Signature | Description |
| --- | --- | --- |
| isSupported | () => boolean | Whether this browser can control a camera at all. false in Node/SSR, false in Firefox, false without getUserMedia. |
| attach | (source: MediaStreamTrack \| MediaStream) => CameraControl | Take control of a video track. A MediaStream resolves to its first video track. |
| readCapabilities | (track: TrackLike) => Capabilities | Pure, never throws. Normalises track.getCapabilities(), including when it does not exist. |
| clamp | (value: number, range: Range) => number | Pure. Clamps into [min, max] and snaps to the step grid measured from min. |
A default export object holds all four plus CameraError, so import CameraTorch from 'camera-torch'
and the IIFE global read the same.
CameraControl
| Member | Type | Description |
| --- | --- | --- |
| can | { torch, zoom, focus, exposure: boolean } | What this camera can do. Re-read from the track on every access, so late-arriving capabilities are picked up. |
| ranges | { zoom?: Range; exposure?: Range } | The device's real ranges. Only present for capabilities it has. |
| focusModes | string[] | e.g. ['continuous', 'manual', 'single-shot']. |
| torchOn | boolean | Whether this control believes the torch is lit. |
| torch(on) | Promise<void> | Switch the torch on or off. |
| toggleTorch() | Promise<boolean> | Flip it; resolves with the new state. |
| zoom(level) | Promise<number> | Clamped and snapped; resolves with the value actually applied. |
| focusMode(mode) | Promise<void> | Rejects if the device does not list that mode. |
| exposure(value) | Promise<number> | Clamped and snapped; resolves with the value applied. |
| settings() | Record<string, unknown> | track.getSettings(), or {} where it does not exist. |
| reset() | Promise<void> | Torch off, zoom to minimum, focus to continuous. Skips capabilities the device lacks. |
| detach() | void | Turn the torch off, drop the ended listener, release the control. |
Capabilities
| Field | Type | Description |
| --- | --- | --- |
| supported | boolean | getCapabilities() existed and returned an object. |
| torch | boolean | Device has a web-controllable flash LED. |
| zoom | Range \| null | Zoom range. |
| focus / focusModes | boolean / string[] | Focus modes the device accepts. |
| exposure | Range \| null | Exposure range. |
| exposureKey | 'exposureCompensation' \| 'exposureTime' \| null | Which constraint exposure() writes. Not interchangeable — see Gotchas. |
| exposureModes | string[] | e.g. ['continuous', 'manual']. |
| raw | Record<string, unknown> | The untouched capabilities object, for anything not modelled here. |
Range is { min: number; max: number; step: number }. A step of 0 means the device reported
none — treat it as "any value in range".
CameraError
Every rejection is a CameraError with a code, the original error on cause, and (for
constraint failures) the blamed constraint.
| code | When |
| --- | --- |
| 'unsupported' | Nothing track-shaped was passed to attach(). This is what SSR hits. |
| 'not-video' | An audio track, or a MediaStream with no video track. |
| 'not-live' | The track is stopped/ended, or the control was detached. |
| 'unsupported-capability' | The device reports no such capability; the write would be a silent no-op. |
| 'out-of-range' | The platform threw OverconstrainedError. err.constraint names the culprit. |
| 'apply-failed' | Anything else applyConstraints() threw, kept on err.cause. |
Exported types
Range, Capabilities, CameraControl, CameraAbilities, CameraRanges, CameraError,
CameraErrorCode, CameraErrorOptions, ExposureKey, TrackLike, StreamLike, and from
camera-torch/react, CameraSource and UseCameraTorch.
Browser support
| Browser | Torch | Zoom / focus / exposure | Notes |
| --- | --- | --- | --- |
| Chrome / Edge for Android | Yes, rear camera | Yes, where the device reports a range | The main target. Needs HTTPS or localhost. |
| Chrome / Edge desktop | Only if the webcam has an LED — almost none do | Rare | can.torch is false; hide the button. |
| Samsung Internet | Yes | Yes | Chromium-based. |
| Safari, iOS and macOS | No | No | WebKit implements neither the torch constraint nor getCapabilities() for these. isSupported() is false. There is no workaround; an iOS torch needs a native app. |
| Firefox, all platforms | No | No | No MediaStreamTrack.getCapabilities(). isSupported() is false, readCapabilities() returns everything absent. |
| Node / SSR | n/a | n/a | Importing is safe, isSupported() is false, attach() throws CameraError('unsupported'). |
When it does not work, it does not work loudly: isSupported() tells you before you render a
button, can.torch tells you per-device, and every setter rejects with a code instead of quietly
doing nothing.
Recipes
QR scanner with a torch button that only appears when it can work
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
const cam = attach(stream);
torchButton.hidden = !cam.can.torch;
torchButton.onclick = () => cam.toggleTorch().catch((err) => toast(err.message));
// Killing the scanner must not kill the battery.
window.addEventListener('pagehide', () => {
cam.detach();
stream.getTracks().forEach((t) => t.stop());
});Document capture: pin the focus, then zoom in on the page
const cam = attach(stream);
if (cam.focusModes.includes('continuous')) await cam.focusMode('continuous');
// Ask for 3x; find out what you got. On a camera that maxes at 2.4x this returns 2.4.
const applied = await cam.zoom(3);
zoomLabel.textContent = `${applied}x`;Auto-torch in a dark room, without a torch-less device throwing
async function lightIfNeeded(cam, luminance) {
if (!cam.can.torch) return false;
try {
await cam.torch(luminance < 0.15);
return cam.torchOn;
} catch (err) {
if (err.code === 'not-live') return false; // camera went away mid-scan
throw err;
}
}Gotchas
- The LED outlives your page. This is the real bug.
track.stop()does not clear a torch that is still applied on many Android devices — the light stays on until another app opens the camera. Alwaysdetach()(ortorch(false)) before stopping the track.detach()is synchronous and fires the off-write without waiting for it; if you need certainty that it landed,await cam.torch(false)yourself first. - The front camera has no torch. Ask for
facingMode: 'environment'. On a device with several rear cameras, the torch belongs to whichever physical camera the track opened — you cannot light the wide lens from the telephoto track. - Some devices need a frame before they admit to anything.
getCapabilities()can return{}for the first few hundred milliseconds.canandrangesre-read on every access, so re-check after the video'sloadedmetadataevent rather than caching the first answer. The React hook already re-reads once the camera has settled. exposureCompensationandexposureTimeare not the same thing. The first is an EV offset around the automatic exposure; the second is a shutter duration in 100µs units that is ignored unlessexposureModeis'manual'.exposure()writes whichever the device reported —capabilities.exposureKeytells you which — and pairsexposureTimewithexposureMode: 'manual'in the sameadvancedentry.- Zoom here is the digital zoom of one camera, not a lens switch. It crops; it does not improve detail. It also does not exist on the vast majority of webcams.
- Two callers, one track.
attach()returns one shared control per track, sodetach()in one component detaches it for all of them. If two parts of your app need the torch, share the control rather than attaching twice and tearing down independently. - HTTPS or nothing.
getUserMedia()needs a secure context.localhostcounts; a LAN IP over plain HTTP does not.
Contributing
git clone https://github.com/vishalmeena2211/camera-torch.git
cd camera-torch
npm install
npm run dev # tsup --watch
npm test # builds, then runs node:test against dist/demo/index.html is both the demo and the end-to-end test: serve the package root over any local
static server, open it, and every automated check reports itself on the page. Anything that needs a
real camera is a labelled button and an honest skip, never a fake pass.
Links
License
MIT © Vishal Meena
