Screenshot

by msfrisbie

HTML

<button style="font-size:4rem">
  TAKE SCREENSHOT
</button>

JavaScript

document.querySelector('button').addEventListener('click', async function() {
  const getDisplayMediaConstraints = {
    video: {
      // frameRate: 5,
      // width: 1920,
      // height: 1080,
      // displaySurface: "window",
      // logicalSurface: true,
    },
    audio: false
  };

  // @ts-ignore
  const stream = await navigator.mediaDevices.getDisplayMedia(getDisplayMediaConstraints);
  const track = stream.getVideoTracks()[0];
  const canvas = document.createElement('canvas');
  const video = document.createElement('video');
  
  video.srcObject = stream;
  video.play();

  canvas.width = track.getSettings().width;
  canvas.height = track.getSettings().height;
  await new Promise((resolve) => setTimeout(resolve, 1000));
  canvas.getContext('2d').drawImage(
    video,
    0,
    0,
    track.getSettings().width,
    track.getSettings().height,
    0,
    0,
    track.getSettings().width,
    track.getSettings().height,
  );

  track.stop();

  canvas.toBlob((blob) => {
    // https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.style.display = "none";
    let url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = "screenshot.png";
    a.click();
    window.URL.revokeObjectURL(url);
  })
})