본문 바로가기

시작하기

GitHub

AI-Assisted Setup으로 플러그인을 설치할 수 있습니다. 다음 명령어로 AI 도구에 Capgo 스킬을 추가하세요:

터미널 창
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

그런 다음 아래 프롬프트를 사용하세요:

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 뒤에 있는 Native preview가 보일 수 있도록 route 또는 앱 배경을 투명하게 설정하세요 (예: 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() 라우트를 벗어날 때 또는 다음 화면에서 카메라를 여는 데 실패할 수 있습니다.
  • 웹: 모바일 브라우저에서 preview를 사용하기 전에 플러그인 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 문자열 대신 디바이스의 절대 파일 경로가 반환됩니다. 파일 경로에서 base64 문자열을 가져오려면 getBase64FromFilePath를 사용하세요.

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

프리뷰 내 특정 지점에 카메라 포커스를 설정합니다.

참고: 이 플러그인은 네이티브 tap-to-focus 제스처 핸들러를 제공하지 않습니다. HTML/JS(예: 오버레이 UI)에서 탭 이벤트를 처리한 후, 정규화된 좌표를 여기에 전달하세요.

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

기기에 지정된 절대 경로에 있는 파일을 삭제합니다. 다음과 같이 생성된 임시 이미지를 빠르게 정리할 때 사용하세요: storeToFile. 웹에서는 지원되지 않으며 에러가 발생합니다.

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.tsupstream에서 public 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.의 구현 세부 사항