Vai al contenuto

Per iniziare

GitHub

Puoi usare il nostro setup assistito dall'IA per installare il plugin. Aggiungi le skill Capgo al tuo strumento di IA usando il seguente comando:

Finestra del terminale
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Poi usa il seguente prompt:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/camera-preview` plugin in my project.

Se preferisci la configurazione manuale, installa il plugin eseguendo questi comandi e segui le istruzioni specifiche per piattaforma qui sotto:

Finestra del terminale
bun add @capgo/camera-preview
bunx cap sync
import { CameraPreview } from '@capgo/camera-preview';

Avvia l'anteprima della fotocamera posteriore dietro la tua UI, scatta una foto e poi fermala per rilasciare la fotocamera.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.start({
position: 'rear',
parent: 'cameraPreview',
toBack: true,
});
const { value } = await CameraPreview.capture({ quality: 90 });
console.log('Photo base64', value);
await CameraPreview.stop();

Monta un elemento a tutto schermo con id="cameraPreview" nel tuo HTML e rendi trasparente lo sfondo della rotta o dell'app, così l'anteprima nativa dietro la WebView sarà visibile (ad esempio ion-content { --background: transparent; } sulle rotte Ionic).

await CameraPreview.start({ position: 'rear', toBack: true });
await CameraPreview.startBarcodeScanner({
formats: ['qr_code', 'code_128'],
detectionInterval: 400,
});
let handled = false;
const barcodeListener = await CameraPreview.addListener('barcodeScanned', async (event) => {
if (handled) return;
const code = event.barcodes[0]?.value;
if (!code) return;
handled = true;
await CameraPreview.stopBarcodeScanner();
await handleScan(code);
});
// When leaving the screen:
await barcodeListener.remove();
await CameraPreview.flip();
await CameraPreview.setFlashMode({ flashMode: 'torch' });
  • Permessi: richiedi l'accesso alla camera (e al microfono se registri video) prima del start.
  • Lifecycle: chiamata stop() quando si esce dalla rotta o la schermata successiva potrebbe non riuscire ad aprire la camera.
  • Web: verifica le API supportate nel README del plugin prima di fare affidamento sulla preview nei browser mobile.

Avvia la camera preview.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.start({ parent: 'parent' });
console.log(result);

Ferma la camera preview.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.stop();

Scatta una foto con la fotocamera.

Se storeToFile was set to true all'avvio della preview, il valore restituito value sarà un percorso file assoluto sul dispositivo invece di una stringa base64. Usa getBase64FromFilePath per ottenere la stringa base64 dal percorso del file.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.capture({ height: 1920 });
console.log(result);

Cattura un singolo frame dallo stream della camera preview.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.captureSample({
quality: 85,
mirrorFrontCamera: false,
});
console.log(result);

Ottiene le modalità flash supportate dalla fotocamera attiva.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSupportedFlashModes();
console.log(result);

Imposta l'aspect ratio della camera preview.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setAspectRatio({} as { aspectRatio: '4:3' | '16:9'; x?: number; y?: number });

Ottiene l'aspect ratio attuale della camera preview.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getAspectRatio();
console.log(result);

Imposta la modalità griglia dell'overlay della camera preview.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setGridMode({ gridMode: 'none' });

Ottiene la modalità griglia attuale dell'overlay della camera preview.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getGridMode();
console.log(result);

Verifica lo stato dei permessi della fotocamera (e opzionalmente del microfono) senza mostrare il prompt di sistema.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.checkPermissions();
// The result holds sensitive values: use it without logging it.

Richiede i permessi per la fotocamera (e il microfono opzionale). Se i permessi sono già stati concessi o negati, viene restituito lo stato attuale senza mostrare prompt. Quando showSettingsAlert è true e i permessi sono negati, verrà mostrato un alert specifico della piattaforma per guidare l'utente nelle impostazioni dell'app.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.requestPermissions();
// The result holds sensitive values: use it without logging it.

Ottiene il campo visivo (FOV) orizzontale della fotocamera attiva. Nota: su alcuni dispositivi potrebbe essere una stima.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getHorizontalFov();
console.log(result);

Ottiene le dimensioni delle immagini supportate da tutte le fotocamere.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSupportedPictureSizes();
console.log(result);

Imposta la modalità flash per la fotocamera attiva.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFlashMode({ flashMode: 'off' });

Passa dalla fotocamera anteriore a quella posteriore.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.flip();

Imposta l'opacità dell'anteprima della fotocamera.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setOpacity({ opacity: 1.0 });

Interrompe una registrazione video in corso.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.stopRecordVideo();
console.log(result);

Avvia la registrazione di un video.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.startRecordVideo({ parent: 'parent' });

Verifica se la camera preview è attualmente attiva.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.isRunning();
console.log(result);

Ottiene tutti i dispositivi camera disponibili.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getAvailableDevices();
console.log(result);

Ottiene lo stato attuale dello zoom, inclusi min/max e le info sull'obiettivo corrente.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoom();
console.log(result);

Restituisce i valori dei pulsanti zoom per un cambio rapido.

  • iOS/Android: include 0.5 se disponibile l'ultra-wide; 1 e 2 se disponibile il wide; 3 se disponibile il telephoto
  • Web: non supportato
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoomButtonValues();
console.log(result);

Imposta il livello di zoom della fotocamera.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setZoom({ level: 1 });

Ottiene la modalità flash attuale.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getFlashMode();
console.log(result);

Passa la camera attiva a quella con l'ID specificato. deviceId.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setDeviceId({ deviceId: 'device-id-123' });

Restituisce l'ID del dispositivo fotocamera attualmente associato. Su Android, se una richiesta per una lente fisica fa fallback su una fotocamera logica, restituisce l'ID della fotocamera logica associata.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getDeviceId();
console.log(result);

Restituisce la dimensione e la posizione attuali dell'anteprima.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getPreviewSize();
console.log(result);

Imposta la dimensione e la posizione dell'anteprima.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.setPreviewSize({
width: 1080,
height: 1920,
});
console.log(result);

Imposta il focus della fotocamera su un punto specifico dell'anteprima.

Nota: il plugin non registra alcun gesture handler nativo per il tap-to-focus. Gestisci i tap nel tuo HTML/JS (ad es. sulla UI sovrapposta), poi passa qui le coordinate normalizzate.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFocus({
x: 1,
y: 1,
});

Elimina un file al percorso assoluto indicato sul dispositivo. Usalo per ripulire rapidamente le immagini temporanee create con storeToFile. Sul web non è supportato e genererà un errore.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.deleteFile({ path: 'path/to/file' });
console.log(result);

Ottiene i safe area insets dei dispositivi. Restituisce l'inset del notch/cutout della fotocamera in base all'orientamento e l'orientamento attuale. In modalità portrait: restituisce l'inset superiore (notch in alto). In modalità landscape: restituisce l'inset sinistro (notch spostato sul lato). Si riferisce specificamente all'area di cutout (notch, punch hole, ecc.) presente su tutti i telefoni moderni.

Android: valori restituiti in dp (pixel logici). iOS: valori restituiti in pixel fisici, escludendo la status bar (solo dimensione del notch/cutout).

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSafeAreaInsets();
console.log(result);

Ottiene l'orientamento corrente del dispositivo in un formato cross-platform.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getOrientation();
console.log(result);

Restituisce le modalità di esposizione supportate dalla fotocamera attiva. Le modalità possono includere: ‘locked’, ‘auto’, ‘continuous’, ‘custom’.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureModes();
console.log(result);

Restituisce la modalità di esposizione corrente.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureMode();
console.log(result);

Imposta la modalità di esposizione.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureMode({ mode: 'AUTO' });

Restituisce l'intervallo supportato per la compensazione dell'esposizione (EV bias).

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureCompensationRange();
console.log(result);

Restituisce la compensazione dell'esposizione (EV bias) corrente.

import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureCompensation();
console.log(result);

Imposta la compensazione dell'esposizione (EV bias). Il valore verrà limitato all'intervallo.

import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureCompensation({ value: 1 });

Definisce le opzioni di configurazione per avviare la camera preview.

export interface CameraPreviewOptions {
/**
* The parent element to attach the video preview to.
* @platform web
*/
parent?: string;
/**
* A CSS class name to add to the preview element.
* @platform web
*/
className?: string;
/**
* The width of the preview in pixels. Defaults to the screen width.
* @platform android, ios, web
*/
width?: number;
/**
* The height of the preview in pixels. Defaults to the screen height.
* @platform android, ios, web
*/
height?: number;
/**
* The horizontal origin of the preview, in pixels.
* @platform android, ios
*/
x?: number;
/**
* The vertical origin of the preview, in pixels.
* @platform android, ios
*/
y?: number;
/**
* The aspect ratio of the camera preview, '4:3' or '16:9' or 'fill'.
* Cannot be set if width or height is provided, otherwise the call will be rejected.
* Use setPreviewSize to adjust size after starting.
*
* @since 2.0.0
*/
aspectRatio?: '4:3' | '16:9';
/**
* Controls how the camera preview fills the available space.
* - 'contain': Fits the entire preview within the space, may show letterboxing (default).
* - 'cover': Fills the entire space, may crop edges of the preview.
* @default "contain"
* @platform android, ios, web
*/
aspectMode?: 'cover' | 'contain';
/**
* The grid overlay to display on the camera preview.
* @default "none"
* @since 2.1.0
*/
gridMode?: GridMode;
/**
* Adjusts the y-position to account for safe areas (e.g., notches).
* @platform ios
* @default false
*/
includeSafeAreaInsets?: boolean;
/**
* If true, places the preview behind the webview.
* @platform android
* @default true
*/
toBack?: boolean;
/**
* Bottom padding for the preview, in pixels.
* @platform android, ios
*/
paddingBottom?: number;
/**
* Whether to rotate the preview when the device orientation changes.
* @platform ios
* @default true
*/
rotateWhenOrientationChanged?: boolean;
/**
* The camera to use.
* @default "rear"
*/
position?: CameraPosition | string;
/**
* If true, saves the captured image to a file and returns the file path.
* If false, returns a base64 encoded string.
* @default false
*/
storeToFile?: boolean;
/**
* If true, prevents the plugin from rotating the image based on EXIF data.
* @platform android
* @default false
*/
disableExifHeaderStripping?: boolean;
/**
* If true, disables the audio stream, preventing audio permission requests.
* @default true
*/
disableAudio?: boolean;
/**
* If true, locks the device orientation while the camera is active.
* @platform android
* @default false
*/
lockAndroidOrientation?: boolean;
/**
* If true, allows the camera preview's opacity to be changed.
* @platform android, web
* @default false
*/
enableOpacity?: boolean;
/**
* If true, disables the visual focus indicator when tapping to focus.
* @platform android, ios
* @default false
*/
disableFocusIndicator?: boolean;
/**
* The `deviceId` of the camera to use. If provided, `position` is ignored.
* @platform ios
*/
deviceId?: string;
/**
* On Android, attempts to bind a physical camera directly when `deviceId` refers to a physical lens.
* Disabled by default because OEM support is inconsistent; when false, Android keeps the current logical-camera fallback behavior.
* @default false
* @platform android
*/
enablePhysicalDeviceSelection?: boolean;
/**
* The initial zoom level when starting the camera preview.
* If the requested zoom level is not available, the native plugin will reject.
* @default 1.0
* @platform android, ios
* @since 2.2.0
*/
initialZoomLevel?: number;
/**
* The vertical positioning of the camera preview.
* @default "center"
* @platform android, ios, web
* @since 2.3.0
*/
positioning?: CameraPositioning;
/**
* If true, enables video capture capabilities when the camera starts.
* @default false
* @platform android
* @since 7.11.0
*/
enableVideoMode?: boolean;
/**
* If true, forces the camera to start/restart even if it's already running or busy.
* This will kill the current camera session and start a new one, ignoring all state checks.
* @default false
* @platform android, ios, web
*/
force?: boolean;
/**
* Sets the quality of video for recording.
* Options: 'low', 'medium', 'high'
* @note On Android requires 'enableVideoMode' to be true
* @note Will affect the entire preview stream for iOS
* @platform ios, android
* @default "high"
*/
videoQuality?: 'low' | 'medium' | 'high';
}

Definisce le opzioni per scattare una foto.

export interface CameraPreviewPictureOptions {
/**
* The maximum height of the picture in pixels. The image will be resized to fit within this height while maintaining aspect ratio.
* If not specified the captured image will match the preview's visible area.
*/
height?: number;
/**
* The maximum width of the picture in pixels. The image will be resized to fit within this width while maintaining aspect ratio.
* If not specified the captured image will match the preview's visible area.
*/
width?: number;
/**
* The quality of the captured image, from 0 to 100.
* Does not apply to `.png` format.
* @default 85
*/
quality?: number;
/**
* The format of the captured image.
* @default "jpeg"
*/
format?: PictureFormat;
/**
* If true, the captured image will be saved to the user's gallery.
* @default false
* @since 7.5.0
*/
saveToGallery?: boolean;
/**
* If true, the plugin will attempt to add GPS location data to the image's EXIF metadata.
* This may prompt the user for location permissions.
* @default false
* @since 7.6.0
*/
withExifLocation?: boolean;
/**
* If true, the plugin will embed a timestamp in the top-right corner of the image.
* @default false
* @since 7.17.0
*/
embedTimestamp?: boolean;
/**
* If true, the plugin will embed the current location in the top-right corner of the image.
* Requires `withExifLocation` to be enabled.
* @default false
* @since 7.18.0
*/
embedLocation?: boolean;
/**
* Sets the priority for photo quality vs. capture speed.
* - "speed": Prioritizes faster capture times, may reduce image quality.
* - "balanced": Aims for a balance between quality and speed.
* - "quality": Prioritizes image quality, may reduce capture speed.
* See https://developer.apple.com/documentation/avfoundation/avcapturephotosettings/photoqualityprioritization for details.
*
* @since 7.21.0
* @platform ios
* @default "speed"
*/
photoQualityPrioritization?: 'speed' | 'balanced' | 'quality';
}

Rappresenta i dati EXIF estratti da un'immagine.

export interface ExifData {
[key: string]: any;
}

Definisce le opzioni per catturare un frame campione dalla camera preview.

export interface CameraSampleOptions {
/**
* The quality of the captured sample, from 0 to 100.
* @default 85
*/
quality?: number;
}

Le modalità flash disponibili per la fotocamera. ‘torch’ è la modalità a luce continua.

export type CameraPreviewFlashMode = 'off' | 'on' | 'auto' | 'torch';
export type GridMode = 'none' | '3x3' | '4x4';
export interface PermissionRequestOptions {
disableAudio?: boolean;
showSettingsAlert?: boolean;
title?: string;
message?: string;
openSettingsButtonTitle?: string;
cancelButtonTitle?: string;
}
export interface CameraPermissionStatus {
camera: PermissionState;
microphone?: PermissionState;
}

Rappresenta le dimensioni delle immagini supportate per una fotocamera orientata in una determinata direzione.

export interface SupportedPictureSizes {
/** The camera direction ("front" or "rear"). */
facing: string;
/** A list of supported picture sizes for this camera. */
supportedPictureSizes: PictureSize[];
}

Definisce le opzioni per impostare l'opacità della camera preview.

export interface CameraOpacityOptions {
/**
* The opacity percentage, from 0.0 (fully transparent) to 1.0 (fully opaque).
* @default 1.0
*/
opacity?: number;
}

Rappresenta una fotocamera fisica sul dispositivo (es. la fotocamera frontale).

export interface CameraDevice {
/** A unique identifier for the camera device. */
deviceId: string;
/** A human-readable name for the camera device. */
label: string;
/** The physical position of the camera on the device. */
position: CameraPosition;
/** A list of all available lenses for this camera device. */
lenses: CameraLens[];
/** The overall minimum zoom factor available across all lenses on this device. */
minZoom: number;
/** The overall maximum zoom factor available across all lenses on this device. */
maxZoom: number;
/** Identifies whether the device is a logical camera (composed of multiple physical lenses). */
isLogical: boolean;
}

Rappresenta le informazioni dettagliate della lente attualmente attiva.

export interface LensInfo {
/** The focal length of the active lens in millimeters. */
focalLength: number;
/** The device type of the active lens. */
deviceType: DeviceType;
/** The base zoom ratio of the active lens (e.g., 0.5x, 1.0x). */
baseZoomRatio: number;
/** The current digital zoom factor applied on top of the base zoom. */
digitalZoom: number;
}

Questa pagina è generata dal src/definitions.ts. Riesegui la sync quando il API pubblico cambia upstream.

Se stai usando Per iniziare per pianificare il comportamento dei media nativi e dell'interfaccia, collegalo a Usare @capgo/camera-preview per la funzionalità nativa in Uso di @capgo/camera-preview, Uso di @capgo/capacitor-live-activities per la funzionalità nativa nella pagina Uso di @capgo/capacitor-live-activities, @capgo/capacitor-live-activities per il dettaglio implementativo in @capgo/capacitor-live-activities, Uso di @capgo/capacitor-video-player per la funzionalità nativa nella pagina Uso di @capgo/capacitor-video-player, e @capgo/capacitor-video-player per il dettaglio implementativo in @capgo/capacitor-video-player.