October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Canvas API

How to Extract a Thumbnail from an MP4 Video with JavaScript

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

To extract a thumbnail from an MP4 video with JavaScript in the browser, load the file into an <video> element, wait for its metadata, seek to the frame you want, wait for the seeked event, and draw that frame to a canvas. Export the canvas as a JPEG or PNG data URL, or as a Blob for uploading or downloading.

Browser-based MP4 thumbnail extraction

This method uses built-in browser APIs: HTMLVideoElement to decode and seek the video, and HTMLCanvasElement to capture and export a frame. It works when the browser can load and decode the MP4 and the page is permitted to read its pixels.

The sequence matters. Wait for loadedmetadata before using the duration or setting currentTime; wait for seeked before drawing. MDN notes that drawImage() works correctly on a video element when its ready state is greater than 1, which occurs after seeking has completed: MDN: CanvasRenderingContext2D.drawImage().

Complete JavaScript implementation

The function below takes a video URL and options, clamps the requested time to the video duration, limits the output width while preserving the aspect ratio, and resolves with both a Blob and a data URL.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
VideoPad Video Editor Free - Create Stunning Movies and Videos with Effects and Transitions [Download]
  • Edit your videos and pictures to perfection with a host of helpful editing tools.
  • Create amazing videos with fun effects and interesting transitions.
  • Record or add audio clips to your video, or simply pull stock sounds from the NCH Sound Library.
  • Enhance your audio tracks with impressive audio effects, like Pan, Reverb or Echo.
  • Share directly online to Facebook, YouTube, and other platforms or burn directly to disc.
function extractThumbnail(videoUrl, {
  time = 0,
  type = 'image/jpeg',
  quality = 0.85,
  maxWidth = 640,
} = {}) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    // Must be set before src for a cross-origin URL whose server allows CORS.
    video.crossOrigin = 'anonymous';

    const fail = () => reject(video.error || new Error('Unable to load video'));
    video.addEventListener('error', fail, { once: true });

    video.addEventListener('loadedmetadata', () => {
      if (!Number.isFinite(video.duration) || video.duration <= 0) {
        reject(new Error('Video has no usable duration'));
        return;
      }
      if (!Number.isFinite(video.videoWidth) || video.videoWidth <= 0 ||
          !Number.isFinite(video.videoHeight) || video.videoHeight <= 0) {
        reject(new Error('Video has no usable dimensions'));
        return;
      }

      const captureTime = Math.min(
        Math.max(0, time),
        Math.max(0, video.duration - 0.001)
      );

      video.addEventListener('seeked', () => {
        const scale = Math.min(1, maxWidth / video.videoWidth);
        const canvas = document.createElement('canvas');
        canvas.width = Math.max(1, Math.round(video.videoWidth * scale));
        canvas.height = Math.max(1, Math.round(video.videoHeight * scale));

        const ctx = canvas.getContext('2d');
        if (!ctx) {
          reject(new Error('Could not create a 2D canvas context'));
          return;
        }

        try {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          canvas.toBlob(blob => {
            if (!blob) {
              reject(new Error('Could not encode thumbnail'));
              return;
            }
            try {
              resolve({ blob, dataUrl: canvas.toDataURL(type, quality) });
            } catch (error) {
              reject(error);
            }
          }, type, quality);
        } catch (error) {
          reject(error);
        }
      }, { once: true });

      video.currentTime = captureTime;
    }, { once: true });

    video.src = videoUrl;
    video.load();
  });
}

Example call for a same-origin or CORS-enabled video:

const { blob, dataUrl } = await extractThumbnail('/media/demo.mp4', {
  time: 4.2,
  type: 'image/jpeg',
  quality: 0.85,
  maxWidth: 640,
});

// Display the data URL directly:
document.querySelector('#preview').src = dataUrl;

// Or upload the Blob:
const form = new FormData();
form.append('thumbnail', blob, 'thumbnail.jpg');
await fetch('/upload-thumbnail', { method: 'POST', body: form });

For an HTML preview, include <img id="preview" alt="Video thumbnail"> on the page. JPEG is suitable for most photographic frames. Use image/png when you need lossless output or transparency in the canvas output; note that a video frame itself typically has no transparent areas.

Choose timestamp, output, and dimensions

Selecting the frame time

Set time in seconds. The example defaults to zero and clamps negative values to the start and values at or beyond the end to just before the duration. A video duration may be unavailable or non-finite for some media; this implementation rejects rather than guessing. For a user-selected timestamp, validate the input as a finite number before calling the function.

Rank #2
Nero Video Maker | Video Editing Software | Create & Edit Videos & Slideshows | 8K, 4K, Full HD | AI-Powered | Lifetime License | 1 PC | Windows 11/10
  • ✔️ Create, Edit & Export Videos & Slideshows: Effortlessly create, edit, and export high-quality videos in HD, 4K, and 8K with powerful editing tools, templates, and effects.
  • ✔️ Multi-Track Video Editing & AI Media Management: Edit multiple tracks with a timeline, advanced effects, and AI-driven tools to manage and optimize your media.
  • ✔️ Over 1000 Templates & Effects: Apply creative filters, transitions, titles, and animations with just a few clicks for professional-quality videos.
  • ✔️ Green Screen (Alpha Channel), PiP Effects & Motion Tracker: Use advanced Green Screen and Picture-in-Picture (PiP) features along with Motion Tracking to add stunning visual effects.
  • ✔️ Lifetime License for 1 PC | No Subscription Fees: Enjoy a one-time purchase with lifetime access, fully compatible with Windows 11, 10. No hidden costs or subscriptions.

Seeking to a timestamp does not guarantee that the frame will correspond to an exact encoded frame boundary. The browser seeks and decodes according to the media timeline. If the chosen moment is visually blank, try a nearby timestamp.

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

Data URL or Blob

canvas.toDataURL(type, quality) returns a string convenient for setting an image’s src. It embeds the encoded image as base64, which can be large for high-resolution captures. canvas.toBlob(callback, type, quality) produces a binary Blob and is generally a better fit for upload, download, or storage workflows. If no image type is supplied to toDataURL(), the canvas defaults to PNG.

Scaling the capture

The sample limits width to 640 pixels and calculates height proportionally. Set maxWidth to a different positive value for your use case. To preserve the source dimensions, choose a maximum width at least as large as video.videoWidth. Canvas dimensions are assigned in pixels; on high-resolution video, scaling down reduces output size and the amount of image data handled.

Rank #3
Sale
Pinnacle Studio 26 | Value-Packed Video Editing & Screen Recording Software [PC Download]
  • Your gateway to advanced video editing software loaded with powerful tools, an intuitive interface, and creative titles, transitions, filters, and effects that deliver quality productions—all with incredible stability and performance
  • Jumpstart a new project with a themed template or easily combine photos and videos across a six-track timeline, then fine-tune every parameter of your production with enhanced keyframe editing and management
  • Tap into tools for Stop Motion Animation, Selective Color, Split Screen Video, Screen Recording, and MultiCam Editing to take your edits to the next level
  • Produce cinema-quality sound by layering video and audio tracks, adjusting the volume, adding fade effects, recording voiceover, and tapping into royalty-free music and sound effects
  • Create high-quality DVDs with 20+ stylized menus and chapters, upload directly to YouTube or Vimeo, or export to popular file formats to share with your audience

Load local files, same-origin videos, and remote MP4s

Local file input

For a file chosen by the user, create a temporary object URL and pass it to the function:

const input = document.querySelector('#video-file');
input.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (!file) return;

  const objectUrl = URL.createObjectURL(file);
  try {
    const { blob } = await extractThumbnail(objectUrl, { time: 2 });
    document.querySelector('#preview').src = URL.createObjectURL(blob);
  } finally {
    URL.revokeObjectURL(objectUrl);
  }
});

Keep the object URL for the lifetime of the media operation; revoke it when no longer needed. If you create a second object URL for the result Blob, retain and revoke that URL when the preview is replaced or removed.

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

Same-origin URL

A video served from the same origin as the page can normally be drawn to canvas and exported without cross-origin configuration. Assign its URL to the video element and use the same event sequence.

Rank #4
Pinnacle Studio 26 Ultimate | Pro-Level Video Editing & Screen Recording Software [PC Key Card]
  • Discover advanced video editing software fully loaded with powerful tools, an intuitive interface, and creative titles, transitions, filters, and effects that produce pro-level productions—all with incredible stability and performance
  • Expertly edit HD, 4K, and 360° video across unlimited tracks, import 8K video, and fine-tune every parameter of your project—positioning, color, transparency, and more—with precise keyframe customization and enhanced keyframe editing
  • Leverage powerful tools like Video Masking, Motion Tracking, complete Color Grading, Smart Object Tracking, Green Screen, Blend Modes, Screen Recording, MultiCam Editing, and more
  • Master your sound with advanced audio editing features including custom noise profiles, pitch scaling, multi-channel sound mixing, voiceover recording tools, and access to royalty-free music and sound effects
  • Create high-quality DVDs with 100+ pro-caliber templates, upload directly to YouTube or Vimeo, or export to popular file formats to share with your audience

Cross-origin URL and CORS

For a video on another origin, set video.crossOrigin = 'anonymous' before assigning src, as the function does. The remote server must also return an appropriate Access-Control-Allow-Origin header for your page. Merely setting the property in JavaScript does not grant permission. Without CORS permission, the browser can load and display the media yet taint the canvas; exporting with toBlob() or toDataURL() then fails with a SecurityError. See MDN: CORS-enabled images and canvas security.

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

When to use a different approach

Browser extraction is a practical choice when the browser supports the MP4’s codec and the page can access the video. It keeps the capture near the user-selected frame and avoids setting up a separate media-processing service. It is not a way around browser decoding or origin-security limits: when the source cannot be decoded or its server does not permit pixel access, use a source you control or a server-side extraction workflow.

If embedding a video with multiple compatible sources, browsers can try the supplied <source> entries in order and signal an error if they all fail. That can improve playback fallback, but the extraction function itself accepts one URL at a time. See MDN: The source element.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Adobe Premiere Elements 2026 | Software Download | Video Editing | 3-year term license | Activation Required [PC/Mac Online Code]
  • Quickly trim and adjust footage with the power of AI and automation.
  • Get started in a snap and grow your skills with Quick, Guided, and Advanced editing modes.
  • Edit and enhance 360° and VR videos and create stop-motion movies.
  • Enhance the action with effects, transitions, expressive text, motion titles, music, and animations.
  • Get your colors just right with easy color correction tools and color grading presets.

Troubleshooting

  • The thumbnail shows the wrong or initial frame: ensure the code waits for seeked after setting currentTime. Do not call drawImage() immediately after setting the time.
  • SecurityError during export: the video is cross-origin without valid CORS permission. Configure the video server to send an appropriate Access-Control-Allow-Origin response, or use a same-origin copy. Setting crossOrigin after src is too late.
  • The video error event fires: check that the URL is reachable, returns video bytes rather than an HTML error page, and points to a format and codec the browser can decode. For embedded playback, provide compatible alternate sources where available.
  • There is no usable duration or frame size: the media may be invalid, incomplete, or not yet decoded as expected. The function waits for metadata; verify the response and inspect the browser console and network request.
  • toBlob() returns no Blob: treat that as an encoding failure, as the example does. Check that the requested output type is supported and that the canvas has nonzero dimensions.
  • The requested time is near the end: seeking exactly to the duration may fail because there is no frame at that position. The function clamps to just before the end; for unusual media, try a slightly earlier time.

Or skip the browser setup

If your goal is a screenshot of a web page rather than a decoded frame from an MP4, ScreenshotNeo is a website screenshot API and MCP server for developers. A single GET request can return a PNG, JPEG, WebP, or PDF. Its clean-shot options accept cookie/consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers AI clients tools including take_screenshot, get_page_info, and capture_pdf.

For example, with your API key, this cURL request captures a web page as WebP. See the ScreenshotNeo API documentation for parameters and response details:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo is not an MP4 frame decoder; use the JavaScript canvas workflow above when you need a timestamped video frame. ScreenshotNeo’s free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

Does this work in every browser?

It depends on whether the browser supports decoding the MP4’s codec and the requested canvas export type. A URL ending in .mp4 alone does not establish codec compatibility.

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

Can I extract several thumbnails from the same MP4?

Yes. Seek to each target time in sequence, wait for a fresh seeked event each time, and draw each completed seek before moving to the next timestamp.

Can I extract a thumbnail from an MP4 URL hosted on another site?

Only if the remote server grants the page CORS access to the video pixels; otherwise canvas export is blocked.

Quick Recap

Bestseller No. 1
VideoPad Video Editor Free - Create Stunning Movies and Videos with Effects and Transitions [Download]
VideoPad Video Editor Free - Create Stunning Movies and Videos with Effects and Transitions [Download]
Edit your videos and pictures to perfection with a host of helpful editing tools.; Create amazing videos with fun effects and interesting transitions.
Bestseller No. 5
Adobe Premiere Elements 2026 | Software Download | Video Editing | 3-year term license | Activation Required [PC/Mac Online Code]
Adobe Premiere Elements 2026 | Software Download | Video Editing | 3-year term license | Activation Required [PC/Mac Online Code]
Quickly trim and adjust footage with the power of AI and automation.; Get started in a snap and grow your skills with Quick, Guided, and Advanced editing modes.
$99.99

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.