跳转到正文

快速入门

GitHub

你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下 prompt:

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

如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:

终端窗口
bun add @capgo/camera-preview
bunx cap sync
import { CameraPreview } from '@capgo/camera-preview';

在 UI 后方启动后置摄像头预览,拍摄静态照片,然后停止以释放摄像头。

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();

使用以下内容挂载全屏元素: id="cameraPreview" 在 HTML 中,并将路由或应用背景设置为透明,以便看到 WebView 后方的原生预览(例如 ion-content { --background: transparent; } (在 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' });
  • 权限:在...之前请求摄像头权限(如果录制视频,还需请求麦克风权限) start.
  • 生命周期: 调用 stop() 离开当前路由时,可能会导致下一个页面无法正常打开摄像头。
  • Web 端:在移动端浏览器中使用预览功能前,请务必先在插件 README 中确认支持的 API。

启动相机预览。

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

停止相机预览。

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

使用相机拍摄照片。

如果 storeToFile 已设置为 true 启动预览时,返回的 value 将是设备上的绝对文件路径,而非 base64 字符串。请使用 getBase64FromFilePath 从文件路径获取 base64 字符串。

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

从相机预览流中截取单帧。

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

获取当前相机支持的闪光灯模式。

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

设置相机预览的宽高比。

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

获取相机预览当前的宽高比。

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

设置相机预览叠加层的网格模式。

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

获取相机预览叠加层当前的网格模式。

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

检查当前摄像头(以及可选的麦克风)权限状态,无需弹出系统对话框。

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

请求摄像头(以及可选的麦克风)权限。如果权限已被授予或拒绝, 则直接返回当前状态,不会弹出提示。当 showSettingsAlert 为 true 且权限被拒绝时, 将显示平台特定的提示,引导用户前往应用设置。

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

获取当前活动摄像头的水平视场角 (FOV)。 注意:在某些设备上这可能是一个估算值。

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

获取所有相机支持的照片尺寸。

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

设置当前活动相机的闪光灯模式。

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

切换前置和后置摄像头。

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

设置相机预览的透明度。

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

停止正在进行的视频录制。

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

开始录制视频。

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

检查相机预览当前是否正在运行。

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

获取所有可用的相机设备。

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

获取当前的缩放状态,包括最小/最大倍数及当前镜头信息。

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

返回用于快速切换的缩放按钮值。

  • iOS/Android:若支持超广角则包含 0.5;若支持广角则包含 1 和 2;若支持长焦则包含 3
  • Web:不支持
import { CameraPreview } from '@capgo/camera-preview';
const result = await CameraPreview.getZoomButtonValues();
console.log(result);

设置摄像头的缩放倍数。

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

获取当前的闪光灯模式。

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

将当前活动的摄像头切换至指定的 deviceId.

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

获取当前绑定的摄像头设备 ID。 在 Android 上,如果物理镜头的请求回退到了逻辑摄像头,则返回绑定的逻辑摄像头 ID。

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

获取当前的预览尺寸和位置。

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

设置预览尺寸和位置。

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

将相机对焦点设置到预览画面中的指定位置。

注意:该插件不会绑定任何原生的点击对焦手势处理。请在 HTML/JS 中(例如覆盖层 UI 上)处理点击,然后把归一化坐标传到这里。

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

删除设备上指定绝对路径的文件。 用于快速清理通过以下方式创建的临时图片: storeToFile。 在 Web 端不支持此操作,会抛出错误。

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

获取设备的安全区域内边距(safe area insets)。 返回随方向变化的刘海/摄像头挖孔内边距以及当前方向。 竖屏模式下:返回顶部内边距(刘海在顶部)。 横屏模式下:返回左侧内边距(刘海移到侧边)。 这专门针对所有现代手机都有的挖孔区域(刘海、挖孔等)。

Android:返回值为 dp(逻辑像素)。 iOS:返回值为物理像素,不含状态栏(仅为纯刘海/挖孔尺寸)。

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

以跨平台格式获取当前设备的屏幕方向。

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

返回当前活动摄像头支持的曝光模式。 模式包括:‘locked’、‘auto’、‘continuous’、‘custom’。

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

返回当前的曝光模式。

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

设置曝光模式。

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

getExposureCompensationRange

“getExposureCompensationRange” 章节

返回支持的曝光补偿 (EV bias) 范围。

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

返回当前的曝光补偿 (EV bias)。

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

设置曝光补偿 (EV bias)。数值将被限制在有效范围内。

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

定义启动相机预览的配置选项。

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

“CameraPreviewPictureOptions” 章节

定义拍照时的相关选项。

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';
}

表示从图像中提取的 EXIF 数据。

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

定义从相机预览中截取采样帧的选项。

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

相机可用的闪光灯模式。“torch” 为常亮模式。

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;
}

表示特定方向相机所支持的图片尺寸。

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

定义设置相机预览透明度的选项。

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

代表设备上的物理摄像头(例如前置摄像头)。

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;
}

代表当前激活镜头的详细信息。

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;
}

本页面由插件的 src/definitions.ts生成。当上游的公共 API 发生变化时,请重新运行 sync。

如果你正在使用 快速入门 来规划原生媒体和界面行为,并将其与 使用 @capgo/camera-preview 在使用 @capgo/camera-preview 时,获取原生能力的方法: 使用 @capgo/capacitor-live-activities 用于使用 @capgo/capacitor-live-activities 时的原生能力, @capgo/capacitor-live-activities 在 @capgo/capacitor-live-activities 中的实现细节, 使用 @capgo/capacitor-video-player 有关使用 @capgo/capacitor-video-player 时的原生能力,以及 @capgo/capacitor-video-player 关于 @capgo/capacitor-video-player. 中的实现细节