DEV Community

Cover image for Using the Pan Tilt Zoom Camera API
Selene Blok
Selene Blok

Posted on • Edited on

Using the Pan Tilt Zoom Camera API

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.
}
Enter fullscreen mode Exit fullscreen mode

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;

  // Lastly we want to get the capabilities of our webcam, the current settings of it and the videotrack itself.
  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.
 }
}

Enter fullscreen mode Exit fullscreen mode

So we now have the ability to view and control a user's webcam, we can now pass arguments to videoTrack.aplyConstraints 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();
}
Enter fullscreen mode Exit fullscreen mode

Demo

I wrote a short interactive demo on codepen, please note that the embed doesn't work since it required a user to confirm a browser API dialog so please click on the link to view it on codepen or view it on ObservableHQ.

Top comments (0)