ngx-webcam-management
Project Status
Current Status: ngx-webcam-management
is currently in active development. While it provides core functionality for webcam management in Angular applications, we are continuously working on improvements and new features.
Compatibility
The ngx-webcam-management
library supports webcam functionality across various platforms:
- Android: Compatible with modern browsers that support WebRTC/UserMedia API.
- iOS: Works on iOS devices with browsers that support the necessary APIs.
- Desktop: Fully functional on current web browsers, including Chrome, Firefox, Safari, and Edge.
Camera Access
- The library allows access to both front and back cameras on devices with multiple cameras.
Roadmap
Our planned developments include:
- Enhanced device selection and user preference management
- Video recording and saving functionality
- Improved cross-browser compatibility
- Performance optimization for various devices
- Enhanced accessibility features
- Expanded documentation and examples
Demo
You can explore a live demonstration of the project through the Live Demo or check out the Demo Project on GitHub for practical insights into its functionalities.
Table of Contents
Overview
ngx-webcam-management
is an Angular library designed to simplify webcam management in web applications. It provides a set of tools for initializing, selecting, and controlling camera devices, making it easier to integrate webcam functionality into your Angular projects.
Client Requirements
Before using the ngx-webcam-management
library, ensure that your client environment meets the following requirements:
-
Browser Compatibility: Use a modern browser that supports HTML5 and WebRTC/UserMedia. Supported browsers include:
- Chrome (version > 53)
- Safari (version > 11)
- Firefox (version > 38)
- Edge (Chromium-based)
-
Hardware: A functioning webcam or camera device connected to the system.
-
Permissions: The application must request and obtain user permissions to access the camera.
Prerequisites
Ensure you have the following installed:
- Node.js: Version 12 or higher
- Angular: Version 11 or higher
- npm: Latest stable version
Installation
To install ngx-webcam-management
, run the following command in your Angular project directory:
npm install ngx-webcam-management --save
Usage
1. Import Module
Import the NgxWebcamManagementModule
into your Angular module:
import { NgxWebcamManagementModule } from 'ngx-webcam-management';
@NgModule({
imports: [
NgxWebcamManagementModule,
],
})
export class AppModule {}
2. Initialize Camera Devices
Use the CameraUtilsService
to initialize camera devices:
constructor(private cameraUtils: CameraUtilsService) {}
async ngOnInit() {
try {
await this.cameraUtils.initializeCameraDevices();
console.log('Camera ready');
} catch (error) {
console.error('Camera init error:', error);
}
}
3. Automatic Camera Initialization
To automatically initialize the camera when your application starts:
- Create a factory function in
camera-init.factory.ts
:
import { CameraUtilsService } from 'ngx-webcam-management';
export function initializeCamera(cameraUtilsService: CameraUtilsService) {
return (): Promise<void> => {
return cameraUtilsService.initializeCameraDevices().catch((error) => {
console.error('Error initializing camera devices:', error);
});
};
}
- Use this factory function in your
app.module.ts
:
import { APP_INITIALIZER } from '@angular/core';
import { initializeCamera } from './camera-init.factory';
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeCamera,
deps: [CameraUtilsService],
multi: true,
},
],
})
export class AppModule {}
4. Selecting and Starting a Camera
To select and start a camera:
The WebcamInitData
configuration object is used to initialize the camera. Here's a detailed breakdown of its properties:
device | CameraDevice | The selected camera device object | selectedCamera |
element | Object | DOM elements for video and canvas | See below |
element.video | HTMLVideoElement | The video element to display the camera feed | this.videoElement.nativeElement |
element.canvas | HTMLCanvasElement | The canvas element for image processing (if needed) | this.canvasElement.nativeElement |
config | Object | Additional configuration options | See below |
config.enabledAudio | boolean | Whether to enable audio | false |
config.present | ResolutionPreset string | The resolution preset to use | ResolutionPreset.VeryHigh |
config.strictAspectRatio | boolean | Whether to strictly maintain the aspect ratio | true |
Example usage:
const config: WebcamInitData = {
device: selectedCamera,
element: {
video: this.videoElement.nativeElement,
canvas: this.canvasElement.nativeElement,
},
config: {
enabledAudio: false,
present: ResolutionPreset.VeryHigh,
strictAspectRatio: true,
},
};
This configuration object is then passed to the startCamera
method of the CameraUtilsService
:
import { Component, ViewChild, ElementRef } from '@angular/core';
import {
CameraUtilsService,
FacingType,
WebcamInitData,
ResolutionPreset,
WebcamInitError,
} from 'ngx-webcam-management';
@Component({
selector: 'app-camera',
template: '<video #videoElement></video><canvas #canvasElement></canvas>',
})
export class CameraComponent {
@ViewChild('videoElement', { static: true }) videoElement!: ElementRef<HTMLVideoElement>;
@ViewChild('canvasElement', { static: true }) canvasElement!: ElementRef<HTMLCanvasElement>;
constructor(private cameraUtilsService: CameraUtilsService) {}
async initializeCamera() {
try {
const selectedCamera = await this.selectCamera();
if (!selectedCamera) {
throw new Error('No camera selected');
}
const config: WebcamInitData = {
device: selectedCamera,
element: {
video: this.videoElement.nativeElement,
canvas: this.canvasElement.nativeElement,
},
config: {
enabledAudio: false,
present: ResolutionPreset.VeryHigh,
strictAspectRatio: true,
},
};
await this.cameraUtilsService.startCamera(config);
const mediaStream = this.cameraUtilsService.getMediaStream();
if (!mediaStream) {
throw new Error('Failed to get media stream');
}
this.videoElement.nativeElement.srcObject = mediaStream;
this.videoElement.nativeElement.onloadedmetadata = () => {
this.videoElement.nativeElement.play();
};
} catch (error) {
if (error instanceof WebcamInitError) {
console.warn('Webcam initialization error:', error.message);
} else {
console.error('Error setting up camera:', error);
}
}
}
private async selectCamera() {
const cameraDevices = this.cameraUtilsService.getAvailableDevices();
if (cameraDevices.length === 0) {
throw new Error('No camera devices found');
}
return this.cameraUtilsService.selectCamera(FacingType.FRONT);
}
}
5. Custom Resolution Presets
Add custom resolution presets:
import { CameraUtilsService } from 'ngx-webcam-management';
export function initializeCamera(cameraUtilsService: CameraUtilsService) {
return (): Promise<void> => {
cameraUtilsService.addCustomResolutionPreset('square-fhd', 1080, 1080);
cameraUtilsService.addCustomResolutionPreset('square-hd', 720, 720);
return cameraUtilsService.initializeCameraDevices();
};
}
5. Capturing Images
To capture an image from the camera feed, you can use the takePicture
method provided by the CameraUtilsService
. Here's an example of how to implement this functionality:
async takePicture() {
try {
const imageDataUrl = await this.cameraUtils.takePicture();
console.log('Picture taken');
} catch (error) {
console.error('Picture error:', error);
}
}
The takePicture
method returns a Promise that resolves with the captured image as a data URL. You can then use this data URL to display the image or send it to a server.
6. Stopping the Camera
When you're done using the camera or when the component is being destroyed, it's important to properly stop the camera to free up resources. You can do this using the stopCamera
method:
ngOnDestroy() {
this.cameraUtils.stopCamera();
}
By calling stopCamera
in the ngOnDestroy
lifecycle hook, you ensure that the camera is properly shut down when the component is destroyed. This is important for releasing system resources and maintaining good performance in your application.
Advanced Features
Custom Resolutions
Add your own resolution presets:
It is recommended to initialize camera device after adding a new resolution. :
cameraUtils.addCustomResolutionPreset('square-hd', 720, 720);
Use it in your config:
config: {
present: 'square-hd',
}