Developer tools
RU EN

Camera

getUserMedia() method returns media streams from camera and microphone

Ready to run
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
const video = document.querySelector('video');
video.srcObject = stream;
// Stop:
stream.getTracks().forEach(t => t.stop());

Parameter constraints - object defining requirements for media stream.
Request audio and video types without additional conditions:

{ audio: true, video: true }

enumerateDevices() method for getting list of available media devices

Ready to run
const devices = await navigator.mediaDevices.enumerateDevices();
devices.forEach(device => {
  console.log(`${device.kind}: ${device.label} id = ${device.deviceId}`);
});

Method returns a Promise that resolves to an array of MediaDeviceInfo objects

Object properties:

  • deviceId - device identifier
  • kind - device type (audioinput, audiooutput, videoinput)
  • label - device name
  • groupId - group identifier

getDisplayMedia() method for capturing screen or part of it

Ready to run
const stream = await navigator.mediaDevices.getDisplayMedia({ 
  video: { cursor: 'always' }, 
  audio: false 
});
const video = document.querySelector('video');
video.srcObject = stream;
// Stop:
stream.getTracks().forEach(t => t.stop());

Parameter constraints - object with capture settings

Main video options:

  • cursor - cursor display ('never', 'always', 'motion')
  • displaySurface - surface type ('monitor', 'window', 'browser')
  • logicalSurface - capture logical surface (true/false)

QR Scanner Reading QR code with camera

Ready to run
// <script src="https://unpkg.com/[email protected]/html5-qrcode.min.js"></script>

const html5QrCode = new Html5Qrcode("qr-reader");

await html5QrCode.start(
  { facingMode: "environment" },
  { fps: 10, qrbox: { width: 250, height: 250 } },
  (decodedText, decodedResult) => {
    console.log('QR code:', decodedText);
  },
  (errorMessage) => {
    // console.error(errorMessage);
  }
);

// Stop:
await html5QrCode.stop();

For QR code reading we use html5-qrcode library

Main parameters:

  • facingMode - camera selection ('user' - front, 'environment' - back)
  • fps - scanning frequency (frames per second)
  • qrbox - scanning area size

Links