Samithu Hettiarachchi
Samithu Hettiarachchi

Reputation: 43

How to use the external web cam on browsers

Hi i have been working on a webpage where webcam is in use. it works fine with the primary laptop camera but my client is using a secondary/external webcam. what should i do to the webpage to use the specific camera instead of using the main laptop camera? or can he set up from windows the secondary camera as the default camera from windows like printers? (i dont have a second webcam test or check this)

Upvotes: 1

Views: 3129

Answers (2)

Maria.B
Maria.B

Reputation: 11

To access the user's camera (and/or microphone) you can use the JavaScript MediaStream API. This allows to access the video and audio captured by these devices through streams.

if ('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {
  // ok, browser supports it
}

Capturing the video stream

const videoStream = await navigator.mediaDevices.getUserMedia({ video: true })

Video requirements

const constraints = {
  video: {
    width: {
      min: 1280,
      ideal: 1920,
      max: 2560,
    },
    height: {
      min: 720,
      ideal: 1080,
      max: 1440,
    },
  },
}

const videoStream = await navigator.mediaDevices.getUserMedia(constraints)

Displaying the video on the page

// considering there is a
// <video autoplay id="video"></video>
// tag in the page
const video = document.querySelector('#video')
const videoStream = await navigator.mediaDevices.getUserMedia(constraints)
video.srcObject = videoStream

Accessing the phone's front and rear cameras

const constraints = {
  video: {
    width: { ... },
    height: { ... },
    facingMode: "environment"
  },
};

videoStream.getTracks().forEach((track) => {
  track.stop()
})

Taking screenshots

// considering there is a
// <canvas id="canvas"></canvas>
// tag in the page
const canvas = document.querySelector('#canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0)

const img = document.createElement('img')
img.src = canvas.toDataURL('image/png')
screenshotsContainer.prepend(img)

Check always the browser settings

Upvotes: 1

SyncToy
SyncToy

Reputation: 131

Try this function

function getConnectedDevices(type, callback) {
    navigator.mediaDevices.enumerateDevices()
        .then(devices => {
            const filtered = devices.filter(device => device.kind === type);
            callback(filtered);
        });
}

getConnectedDevices('videoinput', cameras => console.log('Cameras found', cameras));

There are good examples on the webrtc.org webpage

webrtc.org, Getting started with media devices, Querying media devices

Upvotes: 1

Related Questions