Using the Pan Tilt Zoom Camera API

by Selene Blok

What is the PTZ API?

The PTZ Api is an expansion of the Camera API and was added in Chrome version 87, it allows developers to access the pan, tilt and zoom functionality of a webcam.

That sounds great how do I use it?

Because this API is pretty new you should first check if the browser supports this API.

const supports = navigator.mediaDevices.getSupportedConstraints();
 
if (supports.pan && supports.tilt && supports.zoom) {
  // Browser supports camera PTZ.
}

If the browser does support it we should request a user's permission to "Use & move" the camera. You can do this by calling navigator.mediaDevices.getUserMedia().

async function requestPTZ() {
  try {
    // First we request permission from the user.
    // If they accept it will yield a MediaStream object
    const opts = {
      video: {
        pan: true,
        tilt: true,
        zoom: true
      }
    };
    const stream = await navigator.mediaDevices.getUserMedia(opts);
    // Secondly we can bind this stream to a <video> element on the page.
    document.querySelector("#video").srcObject = stream;
 
    // We can now read the capabilities of the webcam
    // as well as the current settings and the videotrack.
    const [videoTrack] = stream.getVideoTracks();
    const capabilities = videoTrack.getCapabilities();
    const settings = videoTrack.getSettings();
    //...
  } catch (error) {
    throw new Error(error)
    // User denies prompt, or
    // matching media is not available.
  }
}

So we now posses the ability to view and control a user's webcam, we can now pass arguments to videoTrack.applyConstraints to change the pan tilt or zoom like this

async function changeZoom(capabilities, settings, videoTrack) {
  await videoTrack.applyConstraints({
   advanced: [{ zoom: capabilities.zoom.max }]
  })
}
 
if ('zoom' in settings) {
  changeZoom();
}

More articles

My venture into building custom keyboards

How I got into building custom keyboards and what I learned along the way.

Read more

Want to talk about something?

Prefer to skip the contact form?

Send me an email at selene.blok@gmail.com