Saltare al contenuto

Avvio rapido

GitHub

Potete utilizzare la nostra configurazione assistita da AI per installare il plugin. Aggiungete le Capgo competenze al vostro strumento AI utilizzando il seguente comando:

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

Poi utilizzate 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 l'installazione manuale, installa il plugin eseguendo i seguenti comandi e segui le istruzioni specifiche per la piattaforma riportate di seguito.

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

Avvia la preview della fotocamera.

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

Arresta la preview della fotocamera.

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

Cattura una foto dalla fotocamera.

If storeToFile era impostato true quando si avvia la anteprima, il valore restituito value sarà un percorso di file assoluto sul dispositivo al posto di una stringa base64. Utilizza 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 dal flusso di anteprima della fotocamera.

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

Ottiene i modi flash supportati dalla fotocamera attiva.

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

Imposta il rapporto di aspetto della anteprima della camera.

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

Ottiene l'attuale rapporto di aspetto dell'anteprima della camera.

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

Imposta il modo della griglia dell'anteprima della camera sovrapposta.

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

Ottiene l'attuale modo della griglia dell'anteprima della camera sovrapposta.

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

Verifica lo stato di autorizzazione della camera (e della microfono opzionale) senza sollecitare il dialogo del sistema.

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

Richiede le autorizzazioni per la camera (e microfono opzionale). Se le autorizzazioni sono già state concesse o negate, il suo stato attuale viene restituito senza sollecitazione. showSettingsAlert Se è vero e sono negati i permessi, verrà presentato un avviso specifico per la piattaforma che guida l'utente alle 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 orizzontale di visione per la camera attiva. Nota: Questo può essere un'indicazione approssimativa su alcuni dispositivi.

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

Sottosezione intitolata “ottiene dimensioni di immagine supportate”

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

Imposta il modo flash per la camera attiva.

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

Alternare tra le telecamere anteriore e posteriore.

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

Imposta la trasparenza della anteprima della camera.

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

Interrompe la registrazione video in corso.

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

Inizia a registrare un video.

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

Controlla se la preview della camera è attualmente in esecuzione.

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

Ottiene tutti i dispositivi di camera disponibili.

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

Ottiene lo stato di zoom attuale, compresi minimo/maximo e informazioni sulla lente corrente.

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

Restituisce i valori dei pulsanti di zoom per la selezione rapida.

  • iOS/Android: include 0,5 se disponibile ultra-largangolo; 1 e 2 se disponibile largangolo; 3 se disponibile teleobiettivo
  • Web: non supportato
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoomButtonValues();
console.log(result);

Imposta il livello di zoom della camera.

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

Ottiene il modalità di flash corrente.

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

Attiva la camera attiva alla camera specificata deviceId.

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

Ottiene l'ID del dispositivo di camera attualmente associato. Su Android, se una richiesta di lente fisica ricade su una logica camera, questo restituisce l'ID della logica camera associata.

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

Ottiene la dimensione e la posizione della preview attuale.

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

Imposta la dimensione e la posizione della preview.

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

Imposta il focus della camera su un punto specifico nella anteprima.

Nota: Il plugin non attacca alcun gestore di tocco per il focus nativo. Gestisci i tocchi nella tua HTML/JS (ad esempio, sull'interfaccia utente sovrapposta), quindi passa coordinate normalizzate qui.

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

Elimina un file al percorso assoluto specificato sul dispositivo. Usa questo per pulire velocemente le immagini temporanee create con storeToFileNon è supportato sul web e solleverà un errore.

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

Gets the safe area insets for devices. Returns the orientation-aware notch/camera cutout inset and the current orientation. In portrait mode: returns top inset (notch at top). In landscape mode: returns left inset (notch moved to side). This specifically targets the cutout area (notch, punch hole, etc.) that all modern phones have.

Android: Valori restituiti in dp (pixel logici). iOS: Valori restituiti in pixel fisici, escludendo la barra dello stato (solo dimensioni pure notch/cutout).

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

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

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

Restituisce i modi di esposizione supportati dalla camera attiva. I modi possono includere: ‘bloccato’, ‘auto’, ‘continuo’, ‘personalizzato’.

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

Restituisce il modo di esposizione corrente.

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

Imposta il modo di esposizione.

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

Restituisce il range di compensazione di esposizione (bias EV).

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

Restituisce la compensazione di esposizione corrente (bias EV).

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

Imposta la compensazione di esposizione (bias EV). Il valore sarà limitato al range.

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

Definisce le opzioni di configurazione per l'avvio della preview della camera.

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 la cattura di 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 la cattura di un frame di prova dalla anteprima della fotocamera.

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

I modi di flash disponibili per la fotocamera. ‘torch’ è un modo di 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 camera che si trova in una certa 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 preview della camera.

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

Rappresenta una camera fisica sul dispositivo (ad esempio, la camera 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 plugin’s src/definitions.ts. Re-run the sync when the public API changes upstream.

Keep going from Getting Started

Sezione intitolata “Continua da Inizia”

Se stai utilizzando Getting Started per pianificare il comportamento dei media e dell'interfaccia nativi, collega Usando @capgo/camera-preview per la capacità nativa in Usando @capgo/camera-preview, Usando @capgo/capacitor-live-activities per la capacità nativa in Usando @capgo/capacitor-live-activities, @capgo/capacitor-attività-in-vivo per il dettaglio di implementazione in @capgo/capacitor-live-activities, Usando @capgo/capacitor-video-player per la capacità nativa in Usando @capgo/capacitor-video-player, e @capgo/capacitor-player-video per i dettagli di implementazione in @capgo/capacitor-video-player.