### Initialize and Start Camera (Default All)
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/dist/index.html
Initializes the camera with default settings and starts it. Use this for a basic camera setup.
```javascript
var FACING_MODES = JslibHtml5CameraPhoto.FACING_MODES;
var IMAGE_TYPES = JslibHtml5CameraPhoto.IMAGE_TYPES;
// get video and image elements
var videoElement = document.getElementById('videoId');
var imgElement = document.getElementById('imgId');
// get select and buttons elements
var facingModeSelectElement = document.getElementById('facingModeSelectId');
var startCameraDefaultAllButtonElement = document.getElementById('startDefaultAllButtonId');
var startDefaultResolutionButtonElement = document.getElementById('startDefaultResolutionButtonId');
var startMaxResolutionButtonElement = document.getElementById('startMaxResolutionId');
var takePhotoButtonElement = document.getElementById('takePhotoButtonId');
var stopCameraButtonElement = document.getElementById('stopCameraButtonId');
var cameraSettingElement = document.getElementById('cameraSettingsId');
var showInputVideoDeviceInfosButtonElement = document.getElementById('showInputVideoDeviceInfosButtonId');
var inputVideoDeviceInfosElement = document.getElementById('inputVideoDeviceInfosId');
// instantiate JslibHtml5CameraPhoto with the videoElement
var cameraPhoto = new JslibHtml5CameraPhoto.default(videoElement);
function startCameraDefaultAll () {
cameraPhoto.startCamera()
.then(() => {
var log = `Camera started with default All`;
console.log(log);
})
.catch((error) => {
console.error('Camera not started!', error);
});
}
```
--------------------------------
### Start Camera and Capture Photo
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/00-START-HERE.md
A quick example demonstrating how to start the camera and capture a photo as a data URI. Ensure the video element is available and the camera permission is granted before calling startCamera.
```javascript
import CameraPhoto from 'jslib-html5-camera-photo';
const cam = new CameraPhoto(videoElement);
await cam.startCamera();
const photo = cam.getDataUri({imageType: 'jpg'});
```
--------------------------------
### Real-World Photo Booth Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
A complete example demonstrating how to initialize the camera, capture photos, and display them in a photo booth application. It includes starting the camera with specific resolution, capturing photos with JPG format and compression, and stopping the camera.
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
class PhotoBooth {
constructor() {
this.cameraPhoto = new CameraPhoto(document.getElementById('video'));
this.photoCount = 0;
this.bindButtons();
}
bindButtons() {
document.getElementById('start').onclick = () => this.startCamera();
document.getElementById('capture').onclick = () => this.capturePhoto();
document.getElementById('stop').onclick = () => this.stopCamera();
}
async startCamera() {
try {
await this.cameraPhoto.startCamera(FACING_MODES.USER, {width: 1280, height: 720});
this.log('Camera started');
} catch (error) {
this.log('Camera failed: ' + error.name);
}
}
capturePhoto() {
const dataUri = this.cameraPhoto.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9,
isImageMirror: true
});
document.getElementById('preview').src = dataUri;
downloadPhoto(dataUri, 'photo', this.photoCount++);
this.log(`Captured photo ${this.photoCount}`);
}
async stopCamera() {
try {
await this.cameraPhoto.stopCamera();
this.log('Camera stopped');
} catch (error) {
this.log('Camera already stopped');
}
}
log(message) {
document.getElementById('log').textContent = message;
}
}
// Initialize
const booth = new PhotoBooth();
```
--------------------------------
### Vanilla JS Camera Photo Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Demonstrates how to use the CameraPhoto library with plain HTML and JavaScript. Includes setup for video and image elements, buttons, and event handling for taking and stopping the camera.
```html
```
```javascript
import CameraPhoto, { FACING_MODES } from 'jslib-html5-camera-photo';
// get video and image elements from the html
let videoElement = document.getElementById('videoId');
let imgElement = document.getElementById('imgId');
// get buttons elements from the html
let takePhotoButtonElement = document.getElementById('takePhotoButtonId');
let stopCameraButtonElement = document.getElementById('stopCameraButtonId');
// instantiate CameraPhoto with the videoElement
let cameraPhoto = new CameraPhoto(videoElement);
/*
* Start the camera with ideal environment facingMode
* if the environment facingMode is not available, it will fallback
* to the default camera available.
*/
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT)
.then(() => {
console.log('Camera started !');
})
.catch((error) => {
console.error('Camera not started!', error);
});
// function called by the buttons.
function takePhoto () {
const config = {};
let dataUri = cameraPhoto.getDataUri(config);
imgElement.src = dataUri;
}
function stopCamera () {
cameraPhoto.stopCamera()
.then(() => {
console.log('Camera stoped!');
})
.catch((error) => {
console.log('No camera to stop!:', error);
});
}
// bind the buttons to the right functions.
takeButtonElement.onclick = takePhoto;
stopCameraButtonElement.onclick = stopCamera;
```
--------------------------------
### Camera Startup Flow
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/architecture.md
Illustrates the sequence of operations for initializing and starting the camera stream. This flow involves getting stream constraints, requesting user media, and attaching the stream to a video element.
```javascript
startCamera(device, resolution)
↓
stopCamera() [cleanup previous stream]
↓
_getStreamDevice(device, resolution)
↓
MediaServices.getIdealConstraints(device, resolution)
↓
mediaDevices.getUserMedia(constraints)
↓
_gotStream(stream)
├─ _setVideoSrc(stream) [attach to video element]
├─ _setSettings(stream) [read actual settings]
└─ save stream reference
↓
Promise.resolve(stream)
```
--------------------------------
### Start Camera with Default Settings
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Initiates the camera stream using the default camera and resolution. This is a basic way to get the camera feed active.
```javascript
// Start with default camera
cameraPhoto.startCamera()
.then((stream) => {
console.log('Camera started');
})
.catch((error) => {
console.error('Camera error:', error);
});
```
--------------------------------
### Install with Yarn
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Use this command to install the library via Yarn.
```bash
yarn add jslib-html5-camera-photo
```
--------------------------------
### Install with NPM
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Use this command to install the library via NPM.
```bash
npm install jslib-html5-camera-photo
```
--------------------------------
### Install jslib-html5-camera-photo with npm
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Use this command to install the library using npm. This is the standard package manager for Node.js.
```bash
npm install --save jslib-html5-camera-photo
```
--------------------------------
### Initialize CameraPhoto Library
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/00-START-HERE.md
Basic setup for the CameraPhoto library. Import the library and instantiate it with a video element.
```javascript
import CameraPhoto from 'jslib-html5-camera-photo';
const camera = new CameraPhoto(videoElement);
```
--------------------------------
### Start Camera with Options
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Start the camera, specifying facing mode, resolution, or maximum resolution. Use FACING_MODES for camera selection and provide an options object for resolution.
```javascript
// Default camera
cameraPhoto.startCamera()
// Rear-facing camera
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
// Front-facing camera
cameraPhoto.startCamera(FACING_MODES.USER, {})
// Specific resolution
cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480})
// Maximum resolution auto-detection
cameraPhoto.startCameraMaxResolution(FACING_MODES.ENVIRONMENT)
```
--------------------------------
### Complete CameraPhoto Error Handling Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/errors.md
This example demonstrates best practices for handling potential errors during camera startup, including fallback mechanisms for resolution and camera availability. It also includes safe photo capture and cleanup.
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
const cameraPhoto = new CameraPhoto(videoElement);
// 1. Check browser support
if (!navigator.mediaDevices) {
console.error('getUserMedia not supported');
process.exit(1);
}
// 2. Handle camera startup with fallback
function startCameraWithFallback() {
return cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 1920, height: 1080})
.catch(error => {
if (error.name === 'OverconstrainedError') {
console.log('Requested resolution not available, trying lower...');
return cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {});
}
throw error;
})
.catch(error => {
if (error.name === 'NotFoundError') {
console.log('Environment camera not found, trying user camera...');
return cameraPhoto.startCamera(FACING_MODES.USER, {});
}
throw error;
})
.catch(error => {
if (error.name === 'NotAllowedError') {
throw new Error('Camera permission denied');
}
throw error;
});
}
// 3. Safe photo capture and download
function captureAndDownload(prefix, number) {
try {
const dataUri = cameraPhoto.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9
});
if (!dataUri || !dataUri.startsWith('data:')) {
throw new Error('Invalid data URI from capture');
}
downloadPhoto(dataUri, prefix, number);
} catch (error) {
console.error('Capture/download failed:', error);
}
}
// 4. Safe cleanup
function cleanup() {
cameraPhoto.stopCamera()
.then(() => console.log('Camera stopped'))
.catch(() => {}); // Ignore "no stream" errors
}
```
--------------------------------
### Start Camera with Default Settings
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Starts the camera using default facing mode and resolution. Returns a promise that resolves with the stream or rejects with an error.
```javascript
cameraPhoto.startCamera()
.then((stream)=>{
// Handle successful stream
})
.catch((error)=>{
// Handle errors
});
```
--------------------------------
### CameraPhoto Class Initialization and Basic Usage
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Demonstrates how to initialize the CameraPhoto class, start the camera, capture a photo, and stop the camera.
```APIDOC
## Initialization
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
// Initialize with video element
const cameraPhoto = new CameraPhoto(videoElement);
```
## Starting the Camera
```javascript
// Start camera with specific facing mode and resolution (async)
await cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480});
```
## Capturing a Photo
```javascript
// Capture photo as a data URI (synchronous)
const dataUri = cameraPhoto.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9
});
```
## Stopping the Camera
```javascript
// Stop camera and release resources (async)
await cameraPhoto.stopCamera();
```
## Downloading a Photo
```javascript
// Download the captured photo
downloadPhoto(dataUri, 'photo', 1); // Creates: photo-0001.jpg
```
```
--------------------------------
### Start Camera with Facing Mode
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/types.md
Import and use FACING_MODES to select the camera direction when starting the camera.
```javascript
import { FACING_MODES } from 'jslib-html5-camera-photo';
// Start front-facing camera
cameraPhoto.startCamera(FACING_MODES.USER, {});
// Start rear-facing camera
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {});
```
--------------------------------
### Start Camera with Environment Facing
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera specifically using the environment-facing camera. Useful for capturing wider scenes.
```javascript
// Start with environment-facing camera
cameraPhoto.startCamera('environment', {})
.then((stream) => console.log('Environment camera started'))
.catch((error) => console.error(error));
```
--------------------------------
### Start Camera
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Starts the camera stream, optionally specifying facing mode and resolution.
```APIDOC
## Start Camera
### Description
Starts the camera stream, optionally specifying facing mode and resolution.
### Method
```javascript
cameraPhoto.startCamera(facingMode, resolution)
cameraPhoto.startCameraMaxResolution(facingMode)
```
### Parameters
#### Path Parameters
- **facingMode** (FACING_MODES) - Optional - The desired camera facing mode (e.g., FACING_MODES.ENVIRONMENT, FACING_MODES.USER).
- **resolution** (object) - Optional - An object with `width` and `height` properties to specify the desired resolution.
### Examples
```javascript
// Default camera
cameraPhoto.startCamera()
// Rear-facing camera
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
// Front-facing camera
cameraPhoto.startCamera(FACING_MODES.USER, {})
// Specific resolution
cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480})
// Maximum resolution auto-detection
cameraPhoto.startCameraMaxResolution(FACING_MODES.ENVIRONMENT)
```
```
--------------------------------
### React Camera Photo Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Shows how to integrate the CameraPhoto library within a React application. This example utilizes React's refs and component lifecycle methods for camera initialization and control.
```javascript
import React from 'react';
import CameraPhoto, { FACING_MODES } from 'jslib-html5-camera-photo';
class App extends React.Component {
constructor (props, context) {
super(props, context);
this.cameraPhoto = null;
this.videoRef = React.createRef();
this.state = {
dataUri: ''
}
}
componentDidMount () {
// We need to instantiate CameraPhoto inside componentDidMount because we
// need the refs.video to get the videoElement so the component has to be
// mounted.
this.cameraPhoto = new CameraPhoto(this.videoRef.current);
}
startCamera (idealFacingMode, idealResolution) {
this.cameraPhoto.startCamera(idealFacingMode, idealResolution)
.then(() => {
console.log('camera is started !');
})
.catch((error) => {
console.error('Camera not started!', error);
});
}
startCameraMaxResolution (idealFacingMode) {
this.cameraPhoto.startCameraMaxResolution(idealFacingMode)
.then(() => {
console.log('camera is started !');
})
.catch((error) => {
console.error('Camera not started!', error);
});
}
takePhoto () {
const config = {
sizeFactor: 1
};
let dataUri = this.cameraPhoto.getDataUri(config);
this.setState({ dataUri });
}
stopCamera () {
this.cameraPhoto.stopCamera()
.then(() => {
console.log('Camera stoped!');
})
.catch((error) => {
console.log('No camera to stop!:', error);
});
}
render () {
return (
);
}
}
export default App;
```
--------------------------------
### Start Camera with Specific Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Configure the camera to start with a specific width and height. The browser will attempt to match these values, but may use different ones if unavailable.
```javascript
// Specific resolution
cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480})
```
--------------------------------
### Start Camera Stream
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/types.md
Use this snippet to start the camera and obtain a MediaStream object. Inspect the stream directly or use library methods. Ensure proper error handling.
```javascript
cameraPhoto.startCamera(FACING_MODES.USER, {})
.then((stream) => {
// Can inspect stream directly
const videoTracks = stream.getVideoTracks();
console.log('Video tracks:', videoTracks.length);
// Or use camera photo methods instead
const settings = cameraPhoto.getCameraSettings();
})
.catch((error) => console.error(error));
```
--------------------------------
### Start Camera with Max Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Start the camera using a specific device ID and aiming for the maximum resolution.
```javascript
cameraPhoto.startCameraMaxResolution(idealCameraDevice)
```
--------------------------------
### Full Camera Capture Workflow
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Demonstrates the complete process of initializing the camera, starting it, capturing a photo with specific compression settings, displaying a preview, downloading the photo, and finally stopping the camera.
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
// Initialize
const cameraPhoto = new CameraPhoto(document.getElementById('video'));
// Start camera
await cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 1280, height: 720});
// Capture and display
const dataUri = cameraPhoto.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9
});
document.getElementById('preview').src = dataUri;
// Download
downloadPhoto(dataUri, 'photo', 1);
// Cleanup
await cameraPhoto.stopCamera();
```
--------------------------------
### startCamera() Resolution Configuration
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Configure the desired width and height for the camera stream when starting the camera. These are optional parameters.
```javascript
{
width: 1280, // optional
height: 720 // optional
}
```
--------------------------------
### Start Camera with Specific Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera with user-defined resolution constraints. This allows for precise control over the image dimensions.
```javascript
// Start with specific resolution
cameraPhoto.startCamera('user', {width: 640, height: 480})
.then((stream) => console.log('User camera at 640x480 started'))
.catch((error) => console.error(error));
```
--------------------------------
### Start Camera with Maximum Resolution (Any Camera)
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera using any available camera and automatically detects the maximum resolution. This is a convenient option when the specific camera facing is not critical.
```javascript
// Detect maximum resolution, any camera
cameraPhoto.startCameraMaxResolution()
.then((stream) => console.log('Max resolution acquired'))
.catch((error) => console.error(error));
```
--------------------------------
### Initialize and Use CameraPhoto
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Demonstrates the basic workflow of initializing the CameraPhoto library, starting the camera with specific constraints, capturing a photo as a data URI, and stopping the camera. Use this for typical photo capture applications.
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
// Initialize with video element
const cameraPhoto = new CameraPhoto(videoElement);
// Start camera (async)
await cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480});
// Capture photo (synchronous)
const dataUri = cameraPhoto.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9
});
// Stop camera (async)
await cameraPhoto.stopCamera();
// Download photo
downloadPhoto(dataUri, 'photo', 1); // Creates: photo-0001.jpg
```
--------------------------------
### Start Camera with Ideal Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Starts the camera with a specified facing mode and ideal resolution. The resolution is provided as an object with width and height.
```javascript
// example of ideal resolution 640 x 480
cameraPhoto.startCamera(facingMode, {width: 640, height: 480})
.then((stream)=>{
// Handle successful stream
})
.catch((error)=>{
// Handle errors
});
```
--------------------------------
### Start Camera with Facing Mode
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Starts the camera with a specified facing mode (ENVIRONMENT or USER) and default resolution. Use an empty object for default resolution.
```javascript
// environment (camera point to environment)
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
.then((stream)=>{
// Handle successful stream
})
.catch((error)=>{
// Handle errors
});
// OR user (camera point to the user)
cameraPhoto.startCamera(FACING_MODES.USER, {})
.then((stream)=>{
// Handle successful stream
})
.catch((error)=>{
// Handle errors
});
```
--------------------------------
### Method Signature Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Illustrates the expected format for method signatures, including optional parameters and return types.
```javascript
startCamera(idealCameraDevice?: string, idealResolution?: {width?: number, height?: number}): Promise
```
--------------------------------
### Start Camera with Default Resolution and Facing Mode
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/dist/index.html
Starts the camera with a specified facing mode (e.g., 'environment' or 'user') and default resolution. Falls back to the default camera if the preferred mode is unavailable.
```javascript
function startCameraDefaultResolution () {
var facingMode = facingModeSelectElement.value;
cameraPhoto.startCamera(FACING_MODES[facingMode])
.then(() => {
var log = `Camera started with default resolution and ` + `prefered facingMode : ${facingMode}`;
console.log(log);
})
.catch((error) => {
console.error('Camera not started!', error);
});
}
```
--------------------------------
### Start Camera with Maximum Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/dist/index.html
Starts the camera using the maximum available resolution for the specified facing mode. Ideal for capturing high-quality images.
```javascript
function startCameraMaxResolution () {
var facingMode = facingModeSelectElement.value;
cameraPhoto.startCameraMaxResolution(FACING_MODES[facingMode])
.then(() => {
var log = `Camera started with maximum resoluton and ` + `prefered facingMode : ${facingMode}`;
console.log(log);
})
.catch((error) => {
console.error('Camera not started!', error);
});
}
```
--------------------------------
### startCameraMaxResolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/INDEX.md
Starts the camera stream using the maximum available resolution for the selected device.
```APIDOC
## startCameraMaxResolution
### Description
Starts the camera stream, attempting to use the highest possible resolution supported by the selected camera device.
### Parameters
#### Path Parameters
- **device** (FACING_MODES) - Required - Specifies which camera to use (e.g., `FACING_MODES.USER` or `FACING_MODES.ENVIRONMENT`).
- **try** (Resolution) - Optional - An object specifying preferred resolution constraints.
```
--------------------------------
### Data URI Format Examples
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/types.md
Examples of how to use the Data URI returned by getDataUri(). This format is versatile for displaying, downloading, or uploading images.
```javascript
const dataUri = cameraPhoto.getDataUri({imageType: IMAGE_TYPES.JPG});
// Display in image element
document.getElementById('preview').src = dataUri;
// Download to disk
downloadPhoto(dataUri, 'photo', 1);
// Send to server
fetch('/api/upload-photo', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({photo: dataUri})
});
```
--------------------------------
### Start Camera with Facing Mode
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Start the camera using facing modes like USER (front-facing) or ENVIRONMENT (rear-facing). An empty string or undefined uses the default camera.
```javascript
// Front-facing camera
cameraPhoto.startCamera(FACING_MODES.USER, {})
// Rear-facing camera
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
```
```javascript
// Default camera
cameraPhoto.startCamera('', {})
cameraPhoto.startCamera(undefined, {})
cameraPhoto.startCamera() // No parameters
```
--------------------------------
### Camera Photo - Start Camera with Resolution Options
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/types.md
Demonstrates how to initiate camera capture with various resolution constraints. Use an empty object for default resolution, specify both width and height for exact matching, or provide only one dimension to let the browser decide the other. The startCameraMaxResolution() method is used for auto-detection of the maximum available resolution.
```javascript
// No resolution constraints, use default
cameraPhoto.startCamera(FACING_MODES.USER, {});
```
```javascript
// Specific resolution
cameraPhoto.startCamera(FACING_MODES.USER, {width: 640, height: 480});
```
```javascript
// Only width specified, height chosen by browser
cameraPhoto.startCamera(FACING_MODES.USER, {width: 1280});
```
```javascript
// Max resolution auto-detection
cameraPhoto.startCameraMaxResolution(FACING_MODES.ENVIRONMENT);
```
--------------------------------
### startCameraMaxResolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Attempts to start the camera with the maximum possible resolution, falling back to default if necessary. An optional camera device can be specified.
```APIDOC
## startCameraMaxResolution
### Description
Attempts to start the camera with the maximum possible resolution, falling back to default if necessary. An optional camera device can be specified.
### Parameters
#### Path Parameters
- **cameraDevice** (string) - Optional - The `string` of the camera facingMode or deviceId.
### Usage
It will try the range of width `[3840, 2560, 1920, 1280, 1080, 1024, 900, 800, 640, default]` px to take the maximum width of `3840`px if it can't, `2560`px and so on ... until the fall back of the default value of the camera. The facingMode is optional.
```javascript
// It will try the best to get the maximum resolution with the specified facingMode
cameraPhoto.startCameraMaxResolution(cameraDevice)
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
```
```
--------------------------------
### startCameraMaxResolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera and automatically detects the maximum available resolution by testing various resolutions. It prioritizes higher resolutions and falls back to default if necessary.
```APIDOC
## startCameraMaxResolution
### startCameraMaxResolution(idealCameraDevice)
Starts the camera and automatically detects the maximum available resolution.
#### Parameters
- **idealCameraDevice** (string) - Optional - Camera facing mode ('user' or 'environment') or specific deviceId
#### Returns
Promise - Promise that resolves with the active MediaStream at maximum resolution, rejects if all resolution attempts fail.
#### Throws
Rejects with error if all resolution attempts fail
#### Description
Attempts to acquire the maximum camera resolution by progressively testing resolutions in order: 3840px, 2560px, 1920px, 1280px, 1080px, 1024px, 900px, 800px, 640px width, then falls back to default. On iOS, uses optimized constraints with min/ideal values.
#### Example
```javascript
// Detect maximum resolution with user-facing camera
cameraPhoto.startCameraMaxResolution('user')
.then((stream) => {
const settings = cameraPhoto.getCameraSettings();
console.log('Max resolution:', settings.width, 'x', settings.height);
})
.catch((error) => console.error('Max resolution failed:', error));
// Detect maximum resolution, any camera
cameraPhoto.startCameraMaxResolution()
.then((stream) => console.log('Max resolution acquired'))
.catch((error) => console.error(error));
```
```
--------------------------------
### startCamera
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera stream with specified device and resolution constraints. It can fall back to default camera and resolution if ideal constraints cannot be met.
```APIDOC
## startCamera
### startCamera(idealCameraDevice, idealResolution)
Starts the camera stream with specified device and resolution constraints.
#### Parameters
- **idealCameraDevice** (string) - Optional - Camera facing mode ('user' or 'environment') or specific deviceId string
- **idealResolution** (object) - Optional - Desired resolution with shape `{width: number, height: number}`
#### Returns
Promise - Promise that resolves with the active MediaStream, rejects if camera access fails.
#### Throws
Rejects with error if getUserMedia fails or camera access denied
#### Description
Stops any active camera stream, then starts a new stream with the specified constraints. Falls back to default camera/resolution if ideal constraints cannot be met.
#### Example
```javascript
// Start with default camera
cameraPhoto.startCamera()
.then((stream) => {
console.log('Camera started');
})
.catch((error) => {
console.error('Camera error:', error);
});
// Start with environment-facing camera
cameraPhoto.startCamera('environment', {})
.then((stream) => console.log('Environment camera started'))
.catch((error) => console.error(error));
// Start with specific resolution
cameraPhoto.startCamera('user', {width: 640, height: 480})
.then((stream) => console.log('User camera at 640x480 started'))
.catch((error) => console.error(error));
// Start with specific device ID
cameraPhoto.startCamera('deviceId123456', {})
.then((stream) => console.log('Device started'))
.catch((error) => console.error(error));
```
```
--------------------------------
### Example Usage of downloadPhoto
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/download-photo.md
Demonstrates how to capture a photo using CameraPhoto and then download it using the downloadPhoto function with default and custom settings. Ensure CameraPhoto is imported and initialized.
```javascript
import CameraPhoto, { downloadPhoto } from 'jslib-html5-camera-photo';
const videoElement = document.getElementById('video');
const cameraPhoto = new CameraPhoto(videoElement);
// Start camera
cameraPhoto.startCamera()
.then(() => {
// Capture photo
const dataUri = cameraPhoto.getDataUri({
imageType: 'jpg',
imageCompression: 0.9
});
// Download with default settings
// Creates file: photo-0000.jpg
downloadPhoto(dataUri);
// Download with custom prefix
// Creates file: vacation-0001.jpg
downloadPhoto(dataUri, 'vacation', 1);
// Download with high image number
// Creates file: event-0042.png
downloadPhoto(dataUri, 'event', 42);
})
.catch((error) => console.error('Camera error:', error));
```
--------------------------------
### Basic Camera Photo Capture and Download
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/INDEX.md
Demonstrates the basic workflow of starting the camera, capturing a photo as a JPG with compression, downloading it, and stopping the camera. Ensure the video element with id 'video' exists in your HTML.
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, downloadPhoto } from 'jslib-html5-camera-photo';
const camera = new CameraPhoto(document.getElementById('video'));
// Start camera
await camera.startCamera(FACING_MODES.USER, {});
// Capture photo
const dataUri = camera.getDataUri({
imageType: IMAGE_TYPES.JPG,
imageCompression: 0.9
});
// Download
downloadPhoto(dataUri, 'photo', 1);
// Stop
await camera.stopCamera();
```
--------------------------------
### Capture a Photo
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/00-START-HERE.md
Instantiate CameraPhoto, start the camera, and capture a photo as a data URI. Ensure the video element is available in the DOM.
```javascript
import CameraPhoto from 'jslib-html5-camera-photo';
const camera = new CameraPhoto(videoElement);
await camera.startCamera();
const dataUri = camera.getDataUri({});
```
--------------------------------
### Start Camera with Specific Device ID
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/camera-photo.md
Starts the camera using a specific device ID. This is useful when multiple cameras are available and a particular one needs to be selected.
```javascript
// Start with specific device ID
cameraPhoto.startCamera('deviceId123456', {})
.then((stream) => console.log('Device started'))
.catch((error) => console.error(error));
```
--------------------------------
### startCamera() Resolution Parameter
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/README.md
Starts the camera feed with optional resolution settings. You can specify the desired width and height for the camera output.
```APIDOC
## startCamera(device, options)
### Description
Starts the camera feed with optional resolution settings. You can specify the desired width and height for the camera output.
### Parameters
#### Query Parameters
- **device** (string) - Optional - The device ID to use for the camera.
- **options** (object) - Optional - Configuration for the camera resolution.
- **width** (number) - Optional - The desired width for the camera output. Defaults to system default.
- **height** (number) - Optional - The desired height for the camera output. Defaults to system default.
```
--------------------------------
### Start Camera with Width Only
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Specify only the desired width for the camera resolution. The height will be determined by the camera's aspect ratio.
```javascript
// Only width specified, height determined by camera aspect ratio
cameraPhoto.startCamera(FACING_MODES.USER, {width: 1280})
```
--------------------------------
### Type Notation Example
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/00-START-HERE.md
Illustrates TypeScript type notation for function parameters and return types, indicating optional parameters and potential null values.
```typescript
startCamera(device?: string, resolution?: {width?: number, height?: number}): Promise
```
--------------------------------
### startCamera
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Starts the camera stream. It can be configured with a specific camera device (facing mode or device ID) and resolution. The function returns a promise that resolves with the stream or rejects with an error.
```APIDOC
## startCamera
### Description
Starts the camera stream. It can be configured with a specific camera device (facing mode or device ID) and resolution. The function returns a promise that resolves with the stream or rejects with an error.
### Parameters
#### Path Parameters
- **cameraDevice** (string) - Optional - The `string` of the camera facingMode or deviceId.
- **resolution** (object) - Optional - The `object` resolution ex:. `{ width: 640, height: 480 }`.
### Usage
#### Start the default mode (facing Mode & resolution)
If you do not specify any prefer resolution and facing mode, the default is used. The function return a promise. If the promises success it will give you the stream if you want to use it. If it fail, it will give you the error.
```javascript
// default camera and resolution
cameraPhoto.startCamera()
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
```
#### Start with ideal facing Mode & default resolution
```javascript
// environment (camera point to environment)
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
// OR user (camera point to the user)
cameraPhoto.startCamera(FACING_MODES.USER, {})
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
```
#### Start with a user-selected deviceId & default resolution
Instead of facing mode, you can specify the deviceId (camera) that you want to use. To know the device id you can get a list of them using see [Enumerate the available cameras](#enumerate-the-available-cameras), so you can start the camera with the `deviceId` instead of facing mode, e.g.
```javascript
// OR specify the deviceId (use a specific camera)
const deviceId = 'the_string_of_device_id';
cameraPhoto.startCamera(deviceId, {})
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
```
#### Start with ideal (facing Mode & resolution)
```javascript
// example of ideal resolution 640 x 480
cameraPhoto.startCamera(facingMode, {width: 640, height: 480})
.then((stream)=>{
// ...
})
.catch((error)=>{
// ...
});
```
```
--------------------------------
### Start Camera with Default Resolution
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Call startCamera without specifying resolution constraints to use the camera's default settings. This is useful when no specific resolution is required.
```javascript
// No resolution constraints, use camera defaults
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {})
```
--------------------------------
### Catching getUserMedia Errors in startCamera()
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/errors.md
Shows how to catch various DOMException or Error types (e.g., NotAllowedError, NotFoundError, OverconstrainedError) when starting the camera using getUserMedia(). It includes specific checks for different error names and a fallback to retry with lower resolution.
```javascript
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 1920, height: 1080})
.then((stream) => {
console.log('Camera started');
})
.catch((error) => {
// Check specific error conditions
if (error.name === 'NotAllowedError') {
showMessage('Please allow camera access in browser settings');
} else if (error.name === 'NotFoundError') {
showMessage('No camera device found');
} else if (error.name === 'OverconstrainedError') {
// Retry with lower resolution
console.log('Requested resolution not available, trying lower...');
return cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 640, height: 480});
} else if (error.name === 'SecurityError') {
showMessage('Camera requires secure (HTTPS) connection');
} else if (error.name === 'NotReadableError') {
showMessage('Camera is currently in use or hardware error');
} else {
console.error('Unknown camera error:', error);
}
});
```
```javascript
// Retry with progressively relaxed constraints
cameraPhoto.startCamera('environment', {width: 1920, height: 1080})
.catch(() => cameraPhoto.startCamera('environment', {width: 1280, height: 720}))
.catch(() => cameraPhoto.startCamera('environment', {width: 640, height: 480}))
.catch(() => cameraPhoto.startCamera('environment', {}))
.catch((error) => {
console.error('All camera attempts failed:', error);
});
```
--------------------------------
### Get Max Resolution Constraints for Camera
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/media-services.md
Generates media constraints for detecting maximum camera resolution. It implements a progressive fallback strategy, starting with the most aggressive constraints and removing them on subsequent attempts if the ideal resolution is not met. Returns null when all attempts are exhausted.
```javascript
static getMaxResolutionConstraints(idealCameraDevice, numberOfMaxResolutionTry)
```
```javascript
// First attempt - will include all constraints
let constraints = MediaServices.getMaxResolutionConstraints('user', 0);
// Later attempts progressively remove highest values
constraints = MediaServices.getMaxResolutionConstraints('user', 1);
constraints = MediaServices.getMaxResolutionConstraints('user', 4);
// Eventually returns null when exhausted
constraints = MediaServices.getMaxResolutionConstraints('user', 9); // null
```
--------------------------------
### Fallback Camera Start on Failure
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Attempts to start cameras with progressively lower resolutions or different facing modes if the initial attempts fail. Logs an error if all camera start attempts fail.
```javascript
cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 1920, height: 1080})
.catch(() => cameraPhoto.startCamera(FACING_MODES.ENVIRONMENT, {width: 640, height: 480}))
.catch(() => cameraPhoto.startCamera(FACING_MODES.USER, {}))
.catch((error) => console.error('All cameras failed:', error));
```
--------------------------------
### Initialize Camera and Event Listeners
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/public/index.browser.html
Sets up the camera instance and binds event listeners to various UI elements for camera control. It also includes an interval to continuously update camera settings.
```javascript
var FACING_MODES = JslibHtml5CameraPhoto.FACING_MODES;
var IMAGE_TYPES = JslibHtml5CameraPhoto.IMAGE_TYPES;
// get video and image elements
var videoElement = document.getElementById('videoId');
var imgElement = document.getElementById('imgId');
// get select and buttons elements
var facingModeSelectElement = document.getElementById('facingModeSelectId');
var startCameraDefaultAllButtonElement = document.getElementById('startDefaultAllButtonId');
var startDefaultResolutionButtonElement = document.getElementById('startDefaultResolutionButtonId');
var startMaxResolutionButtonElement = document.getElementById('startMaxResolutionId');
var takePhotoButtonElement = document.getElementById('takePhotoButtonId');
var stopCameraButtonElement = document.getElementById('stopCameraButtonId');
var cameraSettingElement = document.getElementById('cameraSettingsId');
var showInputVideoDeviceInfosButtonElement = document.getElementById('showInputVideoDeviceInfosButtonId');
var inputVideoDeviceInfosElement = document.getElementById('inputVideoDeviceInfosId');
// instantiate JslibHtml5CameraPhoto with the videoElement
var cameraPhoto = new JslibHtml5CameraPhoto.default(videoElement);
document.addEventListener('DOMContentLoaded', function () {
// update camera setting
setInterval(() => {
showCameraSettings();
}, 500);
// bind the buttons to the right functions.
startCameraDefaultAllButtonElement.onclick = startCameraDefaultAll;
startDefaultResolutionButtonElement.onclick = startCameraDefaultResolution;
startMaxResolutionButtonElement.onclick = startCameraMaxResolution;
takePhotoButtonElement.onclick = takePhoto;
stopCameraButtonElement.onclick = stopCamera;
showInputVideoDeviceInfosButtonElement.onclick = showInputVideoDeviceInfos;
});
```
--------------------------------
### Constructor
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/README.md
Initializes a new CameraPhoto instance. It requires a video element from the HTML to be passed as an argument.
```APIDOC
## Constructor
### Description
Initializes a new CameraPhoto instance. It requires a video element from the HTML to be passed as an argument.
### Usage
```javascript
import CameraPhoto, { FACING_MODES, IMAGE_TYPES } from 'jslib-html5-camera-photo';
// get your video element with his corresponding id from the html
let videoElement = document.getElementById('videoId');
// pass the video element to the constructor.
let cameraPhoto = new CameraPhoto(videoElement);
```
```
--------------------------------
### Safe Camera Stop and Start Cycle
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Ensures the camera is stopped before attempting to start it again, ignoring any errors if the camera is not currently active. Useful for reinitializing the camera.
```javascript
cameraPhoto.stopCamera()
.then(() => {}) // Do nothing if successful
.catch(() => {}) // Ignore if no camera active
.then(() => cameraPhoto.startCamera(FACING_MODES.USER, {}));
```
--------------------------------
### Minimal Configuration (Defaults)
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/configuration.md
Uses all default settings, resulting in a full-size PNG image.
```javascript
const dataUri = cameraPhoto.getDataUri({})
```
--------------------------------
### Get Camera Settings
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Retrieves the current settings of the camera.
```APIDOC
## Get Camera Settings
### Description
Retrieves the current settings of the camera.
### Method
```javascript
cameraPhoto.getCameraSettings()
```
### Response
#### Success Response (200)
- **settings** (object) - An object containing camera settings like `width`, `height`, and `frameRate`.
```
--------------------------------
### CameraPhoto Class
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/exports.md
The main class for interacting with the camera. It allows starting the camera and capturing photos.
```APIDOC
## Class: CameraPhoto
### Description
Provides functionality to access and control the device's camera for capturing photos.
### Methods
- **constructor(videoElement)**: Initializes the CameraPhoto instance with a video element.
- **startCamera(facingMode, constraints)**: Starts the camera stream. `facingMode` can be `FACING_MODES.USER` or `FACING_MODES.ENVIRONMENT`. `constraints` are optional.
- **getDataUri(options)**: Captures a photo and returns it as a data URI. `options` can include `imageType` (e.g., `IMAGE_TYPES.JPG`).
### Example
```javascript
const camera = new CameraPhoto(videoElement);
camera.startCamera(FACING_MODES.USER, {});
const uri = camera.getDataUri({imageType: IMAGE_TYPES.JPG});
```
```
--------------------------------
### Initialize CameraPhoto
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Initialize the CameraPhoto instance with a video element. Ensure the video element exists in the DOM.
```javascript
const videoElement = document.getElementById('video');
const cameraPhoto = new CameraPhoto(videoElement);
```
--------------------------------
### CameraPhoto Class
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/api-reference/exports.md
The main class for managing camera functionality. It allows starting, stopping, and capturing photos from the camera.
```APIDOC
## Class CameraPhoto
### Description
Provides the main camera management class for interacting with the device's camera.
### Constructor
`new CameraPhoto(videoElement: HTMLVideoElement): CameraPhoto`
### Methods
- `startCamera(idealCameraDevice?: string, idealResolution?: object): Promise`: Starts the camera with optional device and resolution preferences.
- `startCameraMaxResolution(idealCameraDevice?: string): Promise`: Starts the camera using the maximum available resolution.
- `stopCamera(): Promise`: Stops the camera stream.
- `getDataUri(userConfig: object): string`: Captures the current camera frame and returns it as a data URI.
- `getCameraSettings(): object | null`: Retrieves the current camera settings.
- `enumerateCameras(): Promise>`: Lists all available camera devices.
```
--------------------------------
### Error Handling
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Demonstrates how to handle potential errors during camera startup and other operations.
```APIDOC
## Error Handling
```javascript
// Camera startup errors
cameraPhoto.startCamera()
.catch((error) => {
switch (error.name) {
case 'NotAllowedError':
console.error('Camera permission denied');
break;
case 'NotFoundError':
console.error('No camera device found');
break;
case 'OverconstrainedError':
console.error('Requested resolution not supported');
break;
default:
console.error('Camera error:', error);
}
});
// Stop errors (safe to ignore)
cameraPhoto.stopCamera()
.catch(() => {}); // OK if no camera active
```
```
--------------------------------
### Get Camera Settings
Source: https://github.com/mabelanger/jslib-html5-camera-photo/blob/master/_autodocs/quick-reference.md
Retrieve the current camera settings, including resolution and frame rate. Log the settings if available.
```javascript
const settings = cameraPhoto.getCameraSettings();
if (settings) {
console.log(`${settings.width}x${settings.height} @ ${settings.frameRate}fps`);
}
```