DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
Canvas API

How to Capture Screenshots from a Video Source in Electron

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To save a frame from an Electron video stream, assign the stream to an HTML <video> element, wait until it has decoded metadata, draw that frame onto a canvas, and encode the canvas as PNG (or another format). Electron supplies the desktop or window MediaStream; the renderer’s video element and Canvas API produce the still image.

What the capture pipeline does

The reliable sequence is:

  1. Obtain a desktop or window source with Electron’s display-capture APIs.
  2. Expose the resulting MediaStream to the renderer.
  3. Set video.srcObject and start playback.
  4. Wait for non-zero intrinsic dimensions.
  5. Copy the decoded frame with ctx.drawImage(video, ...).
  6. Encode the canvas as a data URL, Blob, or file.

Electron’s desktopCapturer documentation describes the source-enumeration API, while its display-capture example shows the stream-to-video setup. The Canvas drawImage() documentation lists HTMLVideoElement as a valid image source.

Choose a desktop or window source

Use the system picker

navigator.mediaDevices.getDisplayMedia() can open the operating system’s display picker. This is the appropriate path when the user should choose a monitor or window interactively. Electron notes that getDisplayMedia() does not accept a deviceId to silently select a source; selection belongs to the display-capture flow.

Preselect an Electron source

When your application needs to present its own source list, call desktopCapturer.getSources({ types: ['screen', 'window'] }). Each returned DesktopCapturerSource represents a screen or individual window. Configure Electron’s display-media request handler in the main process, then allow the renderer to request the stream.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Guermok Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P 60FPS & 2K 30FPS
  • 【1080P 60FPS Video Capture Card】 This HDMI game capture card is based on USB3.0 high speed transmission port, input resolution up to 4K@30HZ, output resolution up to 2K@30Hz or 1920×1080@60Hz. Type c and USB interface can meet most of the devices in daily life. Easily meet the online capture, real-time recording, online meetings, live gaming and other functions, so you have a better visual enjoyment. Note: For capture use only; requires capture software to function and is not intended for direct screen casting to a monitor or TV
  • 【Ultra Low Latency Screen Sharing】 HDMI capture card is made of good quality aluminum alloy with strong heat dissipation, allowing you to enjoy ultra low latency while live gaming or video recording or live streaming, avoiding blue screens and lag. This HDMI to USBC capture card supports easy recording of good quality audio or HD video and transferring it to your computer or streaming platform, allowing you to record 60 fps HD video directly on your hard drive and real-time preview
  • 【Plug and Play, Easy to Carry】 This HDMI 1080P video capture card does not require any additional drivers or external power supply, just plug and play for fast capture. The capture card is small and lightweight, so you can put it in your bag for emergencies, making it very portable for outdoor live streaming. It's also a great way to share content in game recording, video conference, video recorder and online teaching
  • 【Wide Compatibility USB Capture Card】 Easily streams to Facebook, Youtube or Twitch. With the connection, this HDMI to USB C/3.0 video capture devices can be working on several Operating Systems and various software: Windows 7/ 8/ 10, Mac OS or above, Linux, Android, Laptop, Xbox One, PS3/PS4/PS5, Camera, DVDs, Set Top Box, Webcame, DSLR, Switch/Switch 2, TV BOX, HDTV, Potplayer/VLC, ZOOM, OBS Studio etc.
  • 【Package Content & Note】 1x HD Audio Capture Card , 1x USB 3.0 to USB C Adapter (A-side 3.0, B-side 2.0), 1x user manual. Please note that you need to restart the OBS Studio software after the audio setup is complete, otherwise it will result in no sound output. When using an adapter, if the device is recognized as USB 2.0, try using the other side with the USB-C port. Simply flip the capture card and reconnect it to be recognized as USB 3.0

A minimal main-process setup (adapt the selection policy to your UI) is:

const { app, session, desktopCapturer } = require('electron');

app.whenReady().then(() => {
  session.defaultSession.setDisplayMediaRequestHandler(async (request, callback) => {
    const sources = await desktopCapturer.getSources({
      types: ['screen', 'window']
    });

    // Replace this with a user-selected source from your application UI.
    const source = sources[0];
    if (!source) {
      callback({ video: null });
      return;
    }

    callback({ video: source });
  });
});

In production, do not assume sources[0] is the desired display. Show the source names and thumbnails, let the user choose, and handle cancellation.

Renderer request

After the handler is installed, the renderer can request display media:

async function getDisplayStream() {
  return navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: false
  });
}

Keep the returned stream in application state. Its video track is also how you detect that the user stopped sharing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Attach the stream and capture a PNG

Put a video and canvas in the renderer page:

<video id="preview" autoplay muted playsinline></video>
<canvas id="frameCanvas" hidden></canvas>

The following implementation waits for media data, sizes the canvas to decoded pixels rather than CSS dimensions, and returns a PNG data URL:

const video = document.querySelector('#preview');
const canvas = document.querySelector('#frameCanvas');
const ctx = canvas.getContext('2d');

async function attachStream(stream) {
  video.srcObject = stream;
  await video.play();

  await new Promise((resolve) => {
    if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
      resolve();
    } else {
      video.addEventListener('loadeddata', resolve, { once: true });
    }
  });

  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
}

function capturePng() {
  if (!video.videoWidth || !video.videoHeight) {
    throw new Error('No decoded video frame is available yet');
  }

  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  return canvas.toDataURL('image/png');
}

async function startCapture() {
  const stream = await navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: false
  });
  await attachStream(stream);

  const pngDataUrl = capturePng();
  document.querySelector('#result').src = pngDataUrl;

  stream.getVideoTracks()[0].addEventListener('ended', () => {
    video.srcObject = null;
  });

  return { stream, pngDataUrl };
}

Add <img id="result" alt="Captured frame"> and call startCapture() from a user-activated button. Calling getDisplayMedia() outside an appropriate user gesture can be rejected by the platform.

Download the PNG

A data URL is convenient for previews and small captures:

function downloadDataUrl(dataUrl, filename = 'frame.png') {
  const link = document.createElement('a');
  link.href = dataUrl;
  link.download = filename;
  link.click();
}

For large frames or binary workflows, use a Blob instead of keeping a long base64 string in memory:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Capture Card, 4K HDMI Video Capture Card, Game Capture Card, 1080P 60FPS Video Capture Device, HDMI to USB 3.0 Capture Card for Streaming, Work with Camera/Xbox/PS4/PS5/PC/OBS
  • 【1080P HD High Quality】Capture resolution up to 1080p for video source and it is ideal for all HDMI devices such as PS4, PS3, Xbox One, Xbox 360, Wii U, DVDs, DSLR, Camera, Security Camera and set top box. Note: Video input supports 4K30/60Hz and 1080p120/144Hz. Does not support 4K120Hz/144Hz. Output supports up to 2K30Hz.
  • 【Plug and Play】No driver or external power supply required, true PnP. Once plugged in, the device is identified automatically as a webcam. Detect input and adjust output automatically. Won't occupy CPU, optional audio capture. No freeze with correct setting.
  • 【Compatible with Multiple Systems】suitable for Windows and Mac OS. High speed USB 3.0 technology and superior low latency technology makes it easier for you to transmit live streaming to Twitch, Youtube, Facebook, Twitter, OBS, Potplayer and VLC.
  • 【HDMI LOOP-OUT】Based on the high-speed USB 3.0 technology, it can capture one single channel HD HDMI video signal. There is no delay when you are playing game live.
  • 【Support Mic-in for Commentary】Rybozen capture card has microphone input and you can use it to add external commentary when playing a game. Please note: it only accepts 3.5mm TRS standard microphone headset.
function canvasToBlob(type = 'image/png', quality) {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (blob) resolve(blob);
      else reject(new Error('Canvas encoding failed'));
    }, type, quality);
  });
}

async function saveBlob(blob, filename = 'frame.png') {
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.click();
  URL.revokeObjectURL(url);
}

In an Electron app that needs a native path, send the Blob’s bytes through your preload bridge to a main-process file-save routine. Keep Node integration disabled in untrusted renderer content.

Capture an exact or repeated video frame

A button capture takes the frame currently available to the video element. For animation, synchronization, or a frame-timed grab, use requestVideoFrameCallback(). MDN defines this callback as running when a new video frame is sent to the compositor.

function captureNextFramePng() {
  return new Promise((resolve, reject) => {
    if (!('requestVideoFrameCallback' in HTMLVideoElement.prototype)) {
      try {
        resolve(capturePng());
      } catch (error) {
        reject(error);
      }
      return;
    }

    video.requestVideoFrameCallback(() => {
      try {
        resolve(capturePng());
      } catch (error) {
        reject(error);
      }
    });
  });
}

async function captureLoop() {
  const png = await captureNextFramePng();
  // Store or process png here, then schedule another iteration if required.
  return png;
}

The fallback matters for older embedded Chromium versions. MDN records broad availability of requestVideoFrameCallback() from October 2024, but an Electron application can still run a runtime that predates it. Check the prototype as shown rather than assuming support.

Avoid the zero-dimension race

video.videoWidth or video.videoHeight equal to zero means no usable decoded frame is available. Wait for loadeddata, call play(), or wait for the next video-frame callback before drawing. Do not size the canvas from the element’s CSS width and height if you want the source’s decoded pixel dimensions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Stop capture cleanly

Stop every video track when the user finishes, then detach the stream:

function stopCapture(stream) {
  for (const track of stream.getVideoTracks()) {
    track.stop();
  }
  video.srcObject = null;
}

Stopping tracks releases the display-capture session and prevents a hidden video element from retaining resources. Also remove any frame callbacks or application timers used by a capture loop.

Platform permissions and source behavior

macOS

Electron documents that screen-content capture requires user consent on macOS 10.15 and later. Detect denial and explain how to enable your application in the system’s Screen Recording privacy settings; do not treat an empty source as a successful capture.

Linux with PipeWire

Electron documents a PipeWire caveat: requesting both screen and window types can return only one capture, and the selected source is treated as a window capture in that situation. Test your source-list logic on the desktop environments you support, and offer a clear fallback when the expected monitor/window distinction is unavailable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Video Capture Card, 4K USB3.0 HDMI to USB C, 1080P60FPS HDMI Capture Card for Streaming, Gaming, Video Recording Compatible with Switch, Xbox, PS4/5, OBS,iPad Mac OS Windows,Camera, Zoom(Silver)
  • 【4K HDMI Input, 2K@30Hz Recording】Powered by a true USB 3.0 high-speed interface, the capture card supports up to 4K@30Hz HDMI input and records at 2K@30Hz or 1080P@60Hz. Perfect for gamers, streamers, and professionals who need crisp, smooth video for live streaming, gameplay recording, or online meetings.
  • 【Ultra Low Latency Screen Sharing】Built with a premium aluminum alloy shell and advanced chipset for stable heat dissipation, ensuring ultra-low latency transmission. Capture high-quality video and dual-channel audio in real time—no lag, no frame drop—ideal for Twitch, YouTube, or OBS streaming.
  • 【Easy Plug and Play, Compact & Portable】No driver or external power required—just plug and play via USB 3.0 or Type-C connection to your Windows or macOS computer. Lightweight and compact design makes it easy to carry for outdoor streaming, live shows, or mobile recording setups.
  • 【Wide Compatibility & Multi-Device Support】Compatible with Windows 7 8 10 11, macOS, Linux,Android and supports most popular software such as OBS, Zoom, VLC, Twitch Studio, and more. Works seamlessly with PS4, PS5, Xbox, Switch, DSLR cameras, TV boxes, and other HDMI-output devices for streaming to YouTube, Twitch, etc.
  • 【What You Get】Includes: HDMI Capture Card, USB 3.0 to USB-C Adapter, User Manual. Tips: Make sure your tablet’s OTG function is enabled before connecting. Test your HDMI device with a monitor first to confirm video and audio output, then connect to the Video Capture Card for recording.

Other operating systems

Display-picker UI, consent prompts, and window-visibility rules are platform controlled. Handle rejected promises, an ended track, and a source that disappears before the frame is decoded. Never promise that minimized, protected, or permission-restricted windows will produce pixels.

Troubleshooting

NotAllowedError or a cancelled picker

Cause: The user denied capture, cancelled the picker, or the request was not made from an allowed user action. Fix: Catch the rejection, keep the UI in an idle state, and retry from a clearly labelled button.

The canvas is blank

Cause: Drawing happened before playback or before decoded dimensions became non-zero. Fix: await video.play(), wait for loadeddata or requestVideoFrameCallback(), and verify video.videoWidth and video.videoHeight.

The image is the wrong size

Cause: The canvas was sized from CSS pixels or a fixed preview size. Fix: set both canvas dimensions from video.videoWidth and video.videoHeight immediately before drawing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The first frame is stale

Cause: A draw call ran between compositor updates. Fix: use requestVideoFrameCallback() for frame-timed captures; otherwise capture after playback has produced current data.

Capture continues after the window closes

Cause: Tracks and references were left running. Fix: call track.stop() for every video track, set video.srcObject = null, and stop your capture loop.

Only one kind of source appears on Linux

Cause: PipeWire’s documented behavior when both screen and window types are requested. Fix: account for the returned source type and test separate requests if your product requires distinct choices.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, format, and reliability choices

  • Pixel dimensions: Intrinsic video dimensions preserve the decoded frame; very large displays consume more memory when copied to canvas.
  • Encoding: PNG is lossless and widely usable. JPEG or WebP can reduce file size by passing a different MIME type to toDataURL() or toBlob(); lossy formats accept an optional quality value.
  • Data URL versus Blob: Data URLs simplify previews but add base64 overhead. Blobs are preferable for uploads, repeated captures, and native file handling.
  • Repeated capture: Use frame callbacks rather than an unconstrained timer so work tracks compositor updates. Throttle processing if encoding takes longer than the frame interval.
  • Security: Restrict capture to an explicit user action, keep privileged APIs behind a preload bridge, and validate any source-selection messages crossing IPC.

Or skip the browser setup

If your real goal is a clean screenshot of a web page rather than a desktop video stream, ScreenshotNeo makes one API request and returns PNG, JPEG, WebP, or PDF. Its consent step accepts cookie banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing result. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install the request in your app (see the ScreenshotNeo documentation):

Rank #4
Capture Card 4K HDMI Video Streaming to USB 3.0 1080P 60FPS Capture Device
  • High-Quality Video Capture, 4K HDMI Capture Card Ready: Capture smooth and vibrant video with this 4K HDMI capture card, engineered for gamers and content creators who demand crisp 1080P 60FPS video quality. Whether you're streaming to Twitch or recording gameplay for YouTube, your footage will look professional and detailed
  • Plug-and-Play USB Capture Card, No Drivers Needed: Designed as a USB capture card for streaming, this device works instantly out of the box, just plug into your PC or laptop and start capturing. Fully compatible with popular software like OBS Studio, Streamlabs, and XSplit, making setup quick and stress-free for beginners and pros alike
  • Universal Compatibility PS5, Xbox, Switch & More: Stream or record gameplay from virtually any HDMI-enabled device including Nintendo Switch, PS5, Xbox Series X, DSLR cameras, and PCs. The video capture card for gaming supports seamless passthrough so you can play without lag while your audience watches every frame in real time
  • Low-Latency Performance for Smooth Streaming: This capture card for streaming minimizes delay between gameplay and broadcast, so you get reliable, low-latency capture that works well for competitive gaming, live broadcasts, and podcast sessions. Suitable for those building their channel with high-quality, engaging content
  • Compact & Portable Design for Content Creators: Lightweight and portable, this USB 3.0 capture card works well for creators who travel or switch gaming setups often. Throw it in your bag and stream or record wherever you are, at home, events, LAN parties, streaming or studio sessions
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Every feature is included on every plan. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account to try it without a card.

FAQ

Can Electron return a PNG directly from desktopCapturer?

No. It provides capture sources and a media stream. The renderer must decode the stream and perform the video-to-canvas conversion.

Can I capture only part of a window?

The documented source APIs select screens or windows. For a region, draw the desired rectangle from the video onto a smaller canvas using the source and destination rectangle form of drawImage().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does a CSS-scaled video not improve screenshot resolution?

CSS changes presentation size, not decoded pixels. The screenshot’s maximum source detail is governed by video.videoWidth and video.videoHeight.

Frequently Asked Questions

Can Electron return a PNG directly from desktopCapturer?

No. It provides capture sources and a media stream; the renderer must draw the decoded video frame onto a canvas and encode it.

Can I capture only part of a window?

Yes. Draw a source rectangle into a smaller canvas with the source-and-destination form of Canvas drawImage().

Why does CSS scaling not increase screenshot resolution?

CSS changes display size, while output detail is limited by the video’s intrinsic decoded dimensions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.