JSPM

  • Created
  • Published
  • Downloads 51
  • Score
    100M100P100Q83093F
  • License MIT

A production-grade TypeScript webcam library with callback-based APIs, flexible permission handling, and comprehensive device support

Package Exports

  • ts-webcam
  • ts-webcam/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ts-webcam) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

TS-Webcam 2.0.2

A modern, type-safe TypeScript library for working with webcams in the browser. Provides a clean, promise-based API for camera access, media capture, and device controls with comprehensive TypeScript support.

Features

TypeScript First - Fully typed API with excellent IDE support 🎥 Multi-Device Support - Work with multiple cameras and resolutions 🔐 Permission Management - Granular control over camera and audio permissions 📱 Cross-Platform - Works across desktop and mobile browsers 🎛️ Advanced Controls - Torch, zoom, and focus mode support 🔧 Reactive State - Built-in state management with callbacks 📦 Modular Design - Lightweight and tree-shakeable

Demo

Check out our live demo at https://ts-webcam-docs.vercel.app/

Installation

# npm
npm install ts-webcam

# yarn
yarn add ts-webcam

# pnpm
pnpm add ts-webcam

Getting Started

import { TsWebcam } from "ts-webcam";

// Initialize the webcam instance
const webcam = new TsWebcam();

// Request camera permissions
await webcam.requestPermissions({ video: true });

// Get available video devices
const devices = await webcam.getVideoDevices();

// Configure the webcam
const config = {
    deviceInfo: devices[0],
    preferredResolutions: { width: 1280, height: 720 },
    videoElement: document.getElementById("video") as HTMLVideoElement,

    // Optional callbacks
    onStateChange: (state) => console.log("State changed:", state.status),
    onError: (error) => console.error("Error:", error.message),
    onStreamStart: (stream) => console.log("Stream started"),
    onStreamStop: () => console.log("Stream stopped"),
};

// Start the camera
await webcam.startCamera(config);

// Capture an image
const blob = await webcam.capture();

API Reference

TsWebcam Class

Core Methods

  • requestPermissions(options: PermissionRequestOptions) - Request camera/microphone permissions
  • getVideoDevices() - List available video devices
  • startCamera(config: WebcamConfiguration) - Start camera with configuration
  • stopCamera() - Stop camera and release resources
  • capture() - Capture image as Blob
  • setTorch(enabled: boolean) - Toggle torch/flash
  • setZoom(level: number) - Set zoom level
  • setFocusMode(mode: FocusMode) - Set focus mode
  • getDeviceCapabilities(deviceId: string) - Get device capabilities
  • getState() - Get current webcam state
  • dispose() - Clean up resources

Event Callbacks

  • onStateChange - When webcam state changes
  • onStreamStart - When video stream starts
  • onStreamStop - When video stream stops
  • onError - When an error occurs
  • onPermissionChange - When permission status changes
  • onDeviceChange - When available devices change

Examples

1. State Management

// Get current state
const state = webcam.getState();
console.log("Current status:", state.status);

// Listen for state changes
const config = {
    // ... other config
    onStateChange: (state) => {
        console.log("State changed to:", state.status);
        if (state.error) {
            console.error("Error:", state.error.message);
        }
    },
};

2. Permission Handling

// Request permissions
const permissions = await webcam.requestPermissions({
    video: true,
    audio: false,
});

// Check current permissions
const currentPermissions = await webcam.checkPermissions();
console.log("Camera permission:", currentPermissions.camera);

3. Configuration and Callbacks

const config = {
    deviceInfo: devices[0],
    preferredResolutions: [
        { width: 1920, height: 1080 },
        { width: 1280, height: 720 },
    ],
    enableAudio: false,
    enableMirror: true,

    // Event callbacks
    onStateChange: (state) => {
        console.log("State:", state.status);
    },
    onError: (error) => {
        console.error("Error:", error.message);
    },
    onStreamStart: (stream) => {
        console.log("Stream started");
    },
    onStreamStop: () => {
        console.log("Stream stopped");
    },
};

4. Starting the Camera

try {
    await webcam.startCamera(config);
    console.log("Camera started successfully");
} catch (error) {
    console.error("Failed to start camera:", error.message);
}

5. Stopping the Camera

// Basic stop
webcam.stopCamera();

// With cleanup
webcam.stopCamera();
// Optional: Remove video element source
if (videoElement) {
    videoElement.srcObject = null;
}

6. Error Handling

try {
    await webcam.startCamera(config);
} catch (error) {
    if (error.code === "PERMISSION_DENIED") {
        console.error("Please grant camera permissions");
    } else if (error.code === "DEVICE_NOT_FOUND") {
        console.error("No camera found");
    } else {
        console.error("Camera error:", error.message);
    }
}

7. Capturing Images

// Basic capture
try {
    const blob = await webcam.capture();
    const imageUrl = URL.createObjectURL(blob);
    // Use the image URL
} catch (error) {
    console.error("Capture failed:", error.message);
}

// With image quality (0-1)
const highQualityImage = await webcam.capture({ quality: 0.92 });

8. Torch/Flash Control

// Check if torch is supported
const capabilities = await webcam.getDeviceCapabilities(deviceId);
if (capabilities.hasTorch) {
    // Turn on torch
    await webcam.setTorch(true);

    // Turn off torch
    await webcam.setTorch(false);
}

9. Zoom Control

// Get zoom capabilities
const capabilities = await webcam.getDeviceCapabilities(deviceId);
if (capabilities.maxZoom && capabilities.maxZoom > 1) {
    // Set zoom level (1.0 = no zoom)
    await webcam.setZoom(2.0); // 2x zoom
}

10. Focus Modes

// Check supported focus modes
const capabilities = await webcam.getDeviceCapabilities(deviceId);
if (capabilities.supportedFocusModes?.includes("continuous")) {
    // Set continuous focus
    await webcam.setFocusMode("continuous");
}

// Manual focus
await webcam.setFocusMode("manual");

11. Cleanup

// Stop camera and clean up
webcam.stopCamera();

// When completely done with the webcam instance
webcam.dispose();

// Remove all event listeners
// (automatically done in dispose)

12. Device Capabilities Testing

// Get all devices
const devices = await webcam.getVideoDevices();

// Test each device
for (const device of devices) {
    const capabilities = await webcam.getDeviceCapabilities(device.deviceId);
    console.log(`Device: ${device.label || "Unknown"}`);
    console.log("Capabilities:", {
        hasTorch: capabilities.hasTorch,
        maxZoom: capabilities.maxZoom,
        focusModes: capabilities.supportedFocusModes,
        resolutions: capabilities.supportedResolutions,
    });
}

Browser Support

  • ✅ Chrome 60+
  • ✅ Firefox 55+
  • ✅ Safari 11+
  • ✅ Edge 79+
  • ✅ iOS Safari 11+
  • ✅ Chrome for Android 60+

Demo

Check out the live demo: TS-Webcam Demo

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

MIT © TS-Webcam Team

Advanced Examples

Complete Usage with All Callbacks

import { TsWebcam, TsWebcamState, WebcamError } from "ts-webcam";

const webcam = new TsWebcam();

// Request permissions first
await webcam.requestPermissions({ video: true, audio: false });

// Get available devices
const devices = await webcam.getVideoDevices();
console.log("Available cameras:", devices);

// Configure with all callback handlers
const config = {
    deviceInfo: devices[0],
    preferredResolutions: [
        { name: "HD", width: 1280, height: 720 },
        { name: "FHD", width: 1920, height: 1080 },
    ],
    videoElement: document.getElementById("video") as HTMLVideoElement,
    enableMirror: true,
    debug: true,

    // State management
    onStateChange: (state: TsWebcamState) => {
        console.log(`Status: ${state.status}`);
        if (state.error) {
            console.error("Error:", state.error.message);
        }
    },

    // Stream lifecycle
    onStreamStart: (stream: MediaStream) => {
        console.log("Camera started:", stream.getVideoTracks()[0].label);
    },

    onStreamStop: () => {
        console.log("Camera stopped");
    },

    // Error handling
    onError: (error: WebcamError) => {
        console.error(`Webcam error [${error.code}]:`, error.message);
    },

    // Permission changes
    onPermissionChange: (permissions) => {
        console.log("Permissions changed:", permissions);
    },

    // Device hotplug
    onDeviceChange: (devices) => {
        console.log("Available devices changed:", devices.length);
    },
};

// Start camera
await webcam.startCamera(config);

// Capture image
const captureButton = document.getElementById("capture");
captureButton?.addEventListener("click", async () => {
    try {
        const blob = await webcam.capture();
        const url = URL.createObjectURL(blob);

        const img = document.getElementById("preview") as HTMLImageElement;
        img.src = url;
    } catch (error) {
        console.error("Capture failed:", error);
    }
});

// Cleanup on page unload
window.addEventListener("beforeunload", () => {
    webcam.dispose();
});

Device Capabilities Testing

// Test what a specific camera can do
const deviceId = devices[0].deviceId;
const capabilities = await webcam.getDeviceCapabilities(deviceId);

console.log("Device capabilities:", {
    maxResolution: `${capabilities.maxWidth}x${capabilities.maxHeight}`,
    hasZoom: capabilities.hasZoom,
    hasTorch: capabilities.hasTorch,
    supportedFocusModes: capabilities.supportedFocusModes,
});

Switching Cameras

let currentDeviceIndex = 0;

async function switchCamera() {
    // Stop current camera
    webcam.stopCamera();

    // Switch to next device
    currentDeviceIndex = (currentDeviceIndex + 1) % devices.length;

    // Start with new device
    const newConfig = {
        ...config,
        deviceInfo: devices[currentDeviceIndex],
    };

    await webcam.startCamera(newConfig);
}

Browser Support

  • ✅ Chrome 60+
  • ✅ Firefox 55+
  • ✅ Safari 11+
  • ✅ Edge 79+
  • ✅ iOS Safari 11+
  • ✅ Chrome for Android 60+

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT © TS-Webcam Team