Erste Schritte
Kopiere einen Setup-Prompt mit den Installationsschritten und dem vollständigen Markdown-Guide für dieses Plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/camera-preview`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/camera-preview/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
Installieren
Abschnitt „Installation“Du kannst unser KI-gestütztes Setup nutzen, um das Plugin zu installieren. Füge die Capgo Skills mit dem folgenden Befehl deinem KI-Tool hinzu:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsNutze dann diesen Prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/camera-preview` plugin in my project.Wenn du ein manuelles Setup bevorzugst, installiere das Plugin mit den folgenden Befehlen und befolge die plattformspezifischen Anweisungen unten:
bun add @capgo/camera-previewbunx cap syncImportieren
Abschnitt mit dem Titel „Import“import { CameraPreview } from '@capgo/camera-preview';Quickstart
Abschnitt „Quick start“Starte eine Kamera-Vorschau der Rückkamera hinter deinem UI, mache ein Foto und stoppe sie anschließend, um die Kamera freizugeben.
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();Binde ein Fullscreen-Element mit id="cameraPreview" in dein HTML ein und mache den Hintergrund der Route oder App transparent, damit die native Vorschau hinter der WebView sichtbar wird (z. B. ion-content { --background: transparent; } (auf Ionic-Routen).
Beispiel: Barcode-Overlay
Abschnitt mit dem Titel „Beispiel: Barcode-Overlay“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();Beispiel: Kamera wechseln und Blitz
Abschnitt mit dem Titel „Beispiel: Kamera wechseln und Blitz“await CameraPreview.flip();await CameraPreview.setFlashMode({ flashMode: 'torch' });Häufige Stolperfallen
Abschnitt „Häufige Fallstricke“- Berechtigungen: Kamera anfordern (und Mikrofon, falls Video aufgenommen wird) vor dem
start. - Lifecycle: aufrufen
stop()beim Verlassen der Route oder wenn der nächste Screen die Kamera nicht öffnen kann. - Web: Prüfe die unterstützten APIs im Plugin-README, bevor du dich auf die Vorschau in mobilen Browsern verlässt.
API Übersicht
Abschnitt „API Übersicht“start
Abschnitt „Start“Startet die Kamera-Vorschau.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.start({ parent: 'parent' });console.log(result);Stoppt die Kamera-Vorschau.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.stop();capture
Abschnitt „capture“Erstellt ein Foto mit der Kamera.
Wenn storeToFile wurde auf gesetzt true beim Starten der Vorschau ist der zurückgegebene
value ein absoluter Dateipfad auf dem Gerät statt eines Base64-Strings. Nutze getBase64FromFilePath, um den Base64-String aus dem Dateipfad zu erhalten.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.capture({ height: 1920 });console.log(result);captureSample
Abschnitt „captureSample“Erfasst einen einzelnen Frame aus dem Kamera-Preview-Stream.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.captureSample({ quality: 85, mirrorFrontCamera: false,});console.log(result);getSupportedFlashModes
Abschnitt „getSupportedFlashModes“Ruft die von der aktiven Kamera unterstützten Blitzmodi ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSupportedFlashModes();console.log(result);setAspectRatio
Abschnitt „setAspectRatio“Legt das Seitenverhältnis der Camera Preview fest.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setAspectRatio({} as { aspectRatio: '4:3' | '16:9'; x?: number; y?: number });getAspectRatio
Abschnitt „getAspectRatio“Ruft das aktuelle Seitenverhältnis der Camera Preview ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getAspectRatio();console.log(result);setGridMode
Abschnitt „setGridMode“Legt den Grid-Modus des Camera Preview Overlays fest.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setGridMode({ gridMode: 'none' });getGridMode
Abschnitt „getGridMode“Ruft den aktuellen Grid-Modus des Camera Preview Overlays ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getGridMode();console.log(result);checkPermissions
Abschnitt „checkPermissions“Prüft den aktuellen Kamera- (und optional Mikrofon-) Berechtigungsstatus, ohne den Systemdialog anzuzeigen.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.checkPermissions();// The result holds sensitive values: use it without logging it.requestPermissions
Abschnitt „requestPermissions“Fordert Kamera- (und optionale Mikrofon-) Berechtigungen an. Falls die Berechtigungen bereits erteilt oder abgelehnt wurden,
wird der aktuelle Status ohne Abfrage zurückgegeben. Wenn showSettingsAlert true ist und die Berechtigungen abgelehnt wurden,
wird ein plattformspezifischer Alert angezeigt, der den Nutzer zu den App-Einstellungen leitet.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.requestPermissions();// The result holds sensitive values: use it without logging it.getHorizontalFov
Abschnitt mit dem Titel „getHorizontalFov“Gibt das horizontale Sichtfeld (FOV) der aktiven Kamera zurück. Hinweis: Dies kann auf einigen Geräten nur ein Schätzwert sein.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getHorizontalFov();console.log(result);getSupportedPictureSizes
Abschnitt mit dem Titel „getSupportedPictureSizes“Ruft die unterstützten Bildgrößen aller Kameras ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSupportedPictureSizes();console.log(result);setFlashMode
Abschnitt mit dem Titel „setFlashMode“Legt den Blitzmodus für die aktive Kamera fest.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFlashMode({ flashMode: 'off' });Wechselt zwischen der Front- und Rückkamera.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.flip();setOpacity
Abschnitt mit dem Titel „setOpacity“Legt die Deckkraft der Kamera-Vorschau fest.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setOpacity({ opacity: 1.0 });stopRecordVideo
Abschnitt mit dem Titel „stopRecordVideo“Stoppt eine laufende Videoaufnahme.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.stopRecordVideo();console.log(result);startRecordVideo
Abschnitt mit dem Titel „startRecordVideo“Startet die Videoaufnahme.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.startRecordVideo({ parent: 'parent' });isRunning
Abschnitt mit dem Titel „isRunning“Prüft, ob die Kamera-Vorschau gerade läuft.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.isRunning();console.log(result);getAvailableDevices
Abschnitt mit dem Titel „getAvailableDevices“Gibt alle verfügbaren Kamera-Geräte zurück.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getAvailableDevices();console.log(result);Ruft den aktuellen Zoom-Status ab, inklusive Min/Max und Infos zur aktuellen Linse.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoom();console.log(result);getZoomButtonValues
Abschnitt „getZoomButtonValues“Gibt Zoom-Button-Werte für schnelles Umschalten zurück.
- iOS/Android: 0.5, falls Ultraweitwinkel verfügbar; 1 und 2, falls Weitwinkel verfügbar; 3, falls Teleobjektiv verfügbar
- Web: nicht unterstützt
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoomButtonValues();console.log(result);setZoom
Abschnitt „setZoom“Setzt die Zoomstufe der Kamera.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setZoom({ level: 1 });getFlashMode
Abschnitt „getFlashMode“Ruft den aktuellen Blitzmodus ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getFlashMode();console.log(result);setDeviceId
Abschnitt „setDeviceId“Wechselt die aktive Kamera zur Kamera mit der angegebenen deviceId.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setDeviceId({ deviceId: 'device-id-123' });getDeviceId
Abschnitt „getDeviceId“Gibt die ID des aktuell gebundenen Kamera-Geräts zurück. Auf Android wird bei einem Fallback von einer physischen Linse auf eine logische Kamera die ID der logischen Kamera zurückgegeben.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getDeviceId();console.log(result);getPreviewSize
Abschnitt „getPreviewSize“Ruft die aktuelle Vorschaugröße und -position ab.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getPreviewSize();console.log(result);setPreviewSize
Abschnitt „setPreviewSize“Setzt die Vorschaugröße und -position.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.setPreviewSize({ width: 1080, height: 1920,});console.log(result);setFocus
Abschnitt „setFocus“Setzt den Kamerafokus auf einen bestimmten Punkt in der Vorschau.
Hinweis: Das Plugin fügt keine nativen Tap-to-Focus-Gesture-Handler hinzu. Verarbeite Taps in deinem HTML/JS (z. B. im Overlay-UI) und übergib hier die normalisierten Koordinaten.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setFocus({ x: 1, y: 1,});deleteFile
Abschnitt „deleteFile“Deletes a file at the given absolute path on the device.
Use this to quickly clean up temporary images created with storeToFile.
Im Web wird dies nicht unterstützt und wirft einen Fehler.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.deleteFile({ path: 'path/to/file' });console.log(result);getSafeAreaInsets
Abschnitt „getSafeAreaInsets“Ruft die Safe Area Insets für das Gerät ab. Liefert den orientierungsabhängigen Notch/Kamera-Cutout-Inset sowie die aktuelle Ausrichtung. Im Portrait-Modus: gibt den Top-Inset zurück (Notch oben). Im Landscape-Modus: gibt den Left-Inset zurück (Notch an der Seite). Dies zielt spezifisch auf den Cutout-Bereich (Notch, Punch Hole etc.) moderner Smartphones ab.
Android: Werte werden in dp (logische Pixel) zurückgegeben. iOS: Werte werden in physischen Pixeln zurückgegeben, exklusive Statusleiste (nur reine Notch/Cutout-Größe).
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getSafeAreaInsets();console.log(result);getOrientation
Abschnitt „getOrientation“Gibt die aktuelle Geräteorientierung in einem plattformübergreifenden Format zurück.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getOrientation();console.log(result);getExposureModes
Abschnitt „getExposureModes“Gibt die von der aktiven Kamera unterstützten Belichtungsmodi zurück. Mögliche Modi: ‚locked‘, ‚auto‘, ‚continuous‘, ‚custom‘.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureModes();console.log(result);getExposureMode
Abschnitt „getExposureMode“Gibt den aktuellen Belichtungsmodus zurück.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureMode();console.log(result);setExposureMode
Abschnitt „setExposureMode“Legt den Belichtungsmodus fest.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureMode({ mode: 'AUTO' });getExposureCompensationRange
Abschnitt „getExposureCompensationRange“Gibt den unterstützten Bereich für die Belichtungskorrektur (EV-Bias) zurück.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureCompensationRange();console.log(result);getExposureCompensation
Abschnitt „getExposureCompensation“Gibt die aktuelle Belichtungskorrektur (EV-Bias) zurück.
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getExposureCompensation();console.log(result);setExposureCompensation
Abschnitt „setExposureCompensation“Setzt die Belichtungskorrektur (EV-Bias). Der Wert wird auf den Bereich begrenzt.
import { CameraPreview } from '@capgo/camera-preview';
await CameraPreview.setExposureCompensation({ value: 1 });Typreferenz
Abschnitt mit dem Titel „Typreferenz“CameraPreviewOptions
Abschnitt „CameraPreviewOptions“Definiert die Konfigurationsoptionen zum Starten der 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';}CameraPreviewPictureOptions
Abschnitt „CameraPreviewPictureOptions“Definiert die Optionen zum Aufnehmen eines Fotos.
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';}ExifData
Abschnitt „ExifData“Repräsentiert die aus einem Bild extrahierten EXIF-Daten.
export interface ExifData { [key: string]: any;}CameraSampleOptions
Abschnitt „CameraSampleOptions“Definiert die Optionen zum Erfassen eines Sample-Frames aus der Camera Preview.
export interface CameraSampleOptions { /** * The quality of the captured sample, from 0 to 100. * @default 85 */ quality?: number;}CameraPreviewFlashMode
Abschnitt „CameraPreviewFlashMode“Die verfügbaren Blitzmodi für die Kamera. „torch“ ist ein Dauerlicht-Modus.
export type CameraPreviewFlashMode = 'off' | 'on' | 'auto' | 'torch';GridMode
Abschnitt „GridMode“export type GridMode = 'none' | '3x3' | '4x4';PermissionRequestOptions
Abschnitt „PermissionRequestOptions“export interface PermissionRequestOptions { disableAudio?: boolean; showSettingsAlert?: boolean; title?: string; message?: string; openSettingsButtonTitle?: string; cancelButtonTitle?: string;}CameraPermissionStatus
Abschnitt „CameraPermissionStatus“export interface CameraPermissionStatus { camera: PermissionState; microphone?: PermissionState;}SupportedPictureSizes
Abschnitt „SupportedPictureSizes“Gibt die unterstützten Bildgrößen für eine Kamera in einer bestimmten Ausrichtung an.
export interface SupportedPictureSizes { /** The camera direction ("front" or "rear"). */ facing: string; /** A list of supported picture sizes for this camera. */ supportedPictureSizes: PictureSize[];}CameraOpacityOptions
Abschnitt „CameraOpacityOptions“Definiert die Optionen zum Einstellen der Deckkraft der Kamera-Vorschau.
export interface CameraOpacityOptions { /** * The opacity percentage, from 0.0 (fully transparent) to 1.0 (fully opaque). * @default 1.0 */ opacity?: number;}CameraDevice
Abschnitt „CameraDevice“Repräsentiert eine physische Kamera auf dem Gerät (z. B. die Frontkamera).
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;}LensInfo
Abschnitt „LensInfo“Enthält detaillierte Informationen zum aktuell aktiven Objektiv.
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;}Source of Truth
Abschnitt mit dem Titel „Source of Truth“Diese Seite wird aus dem Plugin generiert src/definitions.ts. Führe den Sync erneut aus, wenn sich das öffentliche API upstream ändert.
Weiter geht's nach Getting Started
Abschnitt: „Weiter geht’s mit Getting Started“Wenn du es nutzt Erste Schritte , um natives Media- und Interface-Verhalten zu planen, verbinde es mit Verwendung von @capgo/camera-preview für die native Funktion in der Verwendung von @capgo/camera-preview, @capgo/capacitor-live-activities verwenden für die native Funktion in „@capgo/capacitor-live-activities verwenden“, @capgo/capacitor-live-activities für die Implementierungsdetails in @capgo/capacitor-live-activities, Verwendung von @capgo/capacitor-video-player für die native Funktion in „@capgo/capacitor-video-player verwenden“, und @capgo/capacitor-video-player für das Implementierungsdetail in @capgo/capacitor-video-player.