Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober 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
Debugging

How to Fix Black Mapbox Screenshots With html2canvas

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

Start by separating two capture paths. If you need to export the Mapbox GL JS WebGL canvas, create the map with preserveDrawingBuffer: true, wait until rendering has settled, and test map.getCanvas().toDataURL() directly. If that direct PNG is correct but an html2canvas result is black or incomplete, the remaining problem is in html2canvas’s DOM-reconstruction path, cross-origin content, canvas dimensions, or the browser/WebGL runtime—not necessarily the Mapbox option.

Why a Mapbox map can turn black

Mapbox GL JS draws the map in a WebGL canvas. html2canvas does something different: it builds a representation from DOM information instead of taking native screen pixels. The two operations can therefore fail independently.

A black result may mean the WebGL drawing buffer was not retained, the capture started before tiles and frames were ready, a cross-origin canvas could not be read, the requested canvas was too large, or the browser’s WebGL implementation behaved differently from your development machine. A solid black image, a transparent image, a white/blank image, and a map with missing labels are useful symptoms, but none identifies one universal cause.

The fastest diagnostic sequence

  1. Verify the live map first. Load the page normally and confirm that the style, tiles, labels, controls, and overlays render before any screenshot code runs.
  2. Check the Map constructor. If the Mapbox canvas itself must be exported, set preserveDrawingBuffer: true. Mapbox documents that this allows map.getCanvas().toDataURL() to export a PNG; the default is false as a performance optimization.
  3. Wait for readiness. Do not capture immediately after constructing the map. Wait for the map’s idle event (or an equivalent application-specific readiness signal), then capture. The event is a useful diagnostic checkpoint, not a guarantee for every style, browser, or headless workflow.
  4. Test direct export separately. Call map.getCanvas().toDataURL('image/png') and open the returned data URL. This tells you whether Mapbox’s own canvas is readable before html2canvas is involved.
  5. Only then debug html2canvas. If direct export works but html2canvas is black, investigate DOM reconstruction, cross-origin resources, output dimensions, and the browser/runtime.

Set preserveDrawingBuffer when exporting the Mapbox canvas

Set the option at map construction time; changing it after the WebGL context already exists is not the documented path.

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
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/your-account/your-style',
  center: [-73.9857, 40.7484],
  zoom: 12,
  preserveDrawingBuffer: true
});

Then wait for rendering and test the canvas directly:

map.once('idle', () => {
  const pngDataUrl = map.getCanvas().toDataURL('image/png');
  console.log(pngDataUrl.slice(0, 32));
  // Example: display it in an image element
  document.querySelector('#preview').src = pngDataUrl;
});

The option has a cost: retaining the drawing buffer is less performance-friendly than Mapbox’s default. Use it when export is required, and avoid enabling it on maps that never need readback.

Use html2canvas only after the direct test

For a DOM capture, call html2canvas after the map signals readiness. The result is still a reconstruction, not a native screenshot, so a successful direct Mapbox export does not prove that every html2canvas capture will include the same pixels.

map.once('idle', async () => {
  try {
    const mapCanvas = map.getCanvas();
    const directPng = mapCanvas.toDataURL('image/png');
    console.log('Direct Mapbox export:', directPng.length, 'characters');

    const captured = await html2canvas(document.querySelector('#map-page'), {
      useCORS: true,
      backgroundColor: null,
      logging: true
    });

    document.querySelector('#html2canvas-preview').src =
      captured.toDataURL('image/png');
  } catch (error) {
    console.error('Capture failed:', error);
  }
});

useCORS can help html2canvas request images with CORS enabled, but it cannot override a server that does not grant permission. Keep the direct PNG and html2canvas PNG as separate test artifacts; comparing them narrows the fault quickly.

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

Direct canvas export versus DOM reconstruction

Question Mapbox canvas export html2canvas capture
What is captured? The WebGL canvas pixels owned by Mapbox. A representation rebuilt from DOM information.
Key setting preserveDrawingBuffer: true before map creation. html2canvas options and resources that it can read.
Readiness concern Map frames and tile activity must have settled. Map readiness plus DOM, image, font, and canvas processing.
Cross-origin exposure Canvas readback can be blocked when content makes the canvas tainted. Cross-origin images or canvases may be skipped or unreadable.
Large output risk WebGL and browser limits still apply. Oversized output can be blank or partial; limits vary by browser and platform.

Neither method is a universal winner. Choose direct export when the map itself is the deliverable. Choose html2canvas when you need a composed DOM region containing the map and surrounding UI, then validate the exact browser and page combination you deploy.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Readiness: capture the map after it is actually rendered

Use idle as a checkpoint

Mapbox’s idle event is useful when a screenshot workflow otherwise races the first style, source, or tile work. Register the listener before the operation that triggers the capture, and make sure your test map can reach the event.

function captureWhenIdle(map, element) {
  return new Promise((resolve, reject) => {
    const onIdle = async () => {
      try {
        const direct = map.getCanvas().toDataURL('image/png');
        const domCanvas = await html2canvas(element);
        resolve({ direct, domCanvas });
      } catch (err) {
        reject(err);
      }
    };
    map.once('idle', onIdle);
  });
}

When idle is not enough

Applications that continually animate, refresh data, or add sources may never become meaningfully idle. In those cases, define readiness in your own code: wait for the style and required sources, stop animations, ensure the target overlays are visible, and use a short application-specific delay only after those conditions are true. Treat any delay as a workaround for your page, not a universal timing rule.

Cross-origin and tainted-canvas checks

A canvas becomes difficult or impossible to read when it contains resources that the browser does not permit your page to read. Check tile, image, sprite, and custom-layer origins, response headers, and any third-party canvas drawn into the map. A SecurityError from toDataURL(), missing imagery, or an html2canvas warning about blocked resources points here.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Serve images and other drawn assets from the same origin when practical.
  • For cross-origin images, configure the server to send an appropriate CORS header and request the image with CORS enabled.
  • Do not assume html2canvas’s useCORS can fix missing server permission.
  • Test with a minimal style and no custom imagery; add layers back until the failure returns.

Canvas size, viewport, and browser limits

Blank or partial output can result when the requested width, height, device-pixel ratio, or full-page dimensions exceed what the browser and platform can allocate. The limits differ across browsers and devices, so avoid treating any single published maximum as universal.

  • Start with the visible map viewport rather than a very tall full-page capture.
  • Reduce html2canvas scale or output dimensions for a diagnostic capture.
  • Capture sections separately and stitch them outside the browser if a full document is too large.
  • Compare a normal-density capture with a retina-density capture; a failure only at higher scale indicates a size or memory boundary.

A minimal reproducible test

Strip the page to one map, one known-good style, and a modest viewport. Create the map with preserveDrawingBuffer: true, wait for idle, and run both exports:

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
map.once('idle', async () => {
  const direct = map.getCanvas().toDataURL('image/png');
  console.log('direct export OK:', direct.startsWith('data:image/png'));

  const result = await html2canvas(document.getElementById('map'));
  const domExport = result.toDataURL('image/png');
  console.log('html2canvas export OK:', domExport.startsWith('data:image/png'));
});

If this minimal page works, reintroduce your application CSS, controls, custom layers, remote images, and full-page dimensions one at a time. If direct export fails in the minimal page, focus on WebGL context, Mapbox initialization, browser hardware acceleration, and canvas readback before changing html2canvas options.

Troubleshooting by symptom

The map is black on screen before capture

This is not a screenshot problem. Check WebGL2 support (required by current Mapbox GL JS), the browser’s hardware-acceleration setting, WebGL context errors, style and token configuration, and the console. Fix normal rendering first.

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.

The map looks correct, but direct toDataURL() is black or throws

Confirm that preserveDrawingBuffer: true was present in the original constructor. Then retest after idle. A thrown security error indicates a readback or cross-origin restriction; a blank result at large dimensions suggests a canvas-size or memory limit.

Direct PNG works, html2canvas is black

That result separates Mapbox export from DOM reconstruction. Confirm that the selector passed to html2canvas contains the map, enable diagnostic logging, test useCORS where appropriate, remove overlays and remote images temporarily, and lower the capture scale. Inspect the target browser rather than adding more Mapbox options.

The image is blank or only partly drawn

Capture after readiness, reduce dimensions, and test a viewport-sized element. Check whether a CSS transform, hidden ancestor, clipping rule, or animation changes what html2canvas sees. A partial image can also indicate a browser canvas limit.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Tiles or labels are missing

Wait for the relevant source and tile work, verify network responses, and test for cross-origin restrictions. If the map is animated or data is refreshed continuously, pause that activity for the capture.

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

It works locally but fails in headless automation

Pin the browser and operating-system versions used in automation, verify WebGL availability, use a consistent viewport and device scale, and capture only after the same readiness signal in every run. Compare a direct Mapbox PNG with the html2canvas output inside that exact runtime.

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

Performance, reliability, and operational choices

  • Performance: retaining the drawing buffer can reduce rendering efficiency; enable it only on maps that need export.
  • Reliability: readiness, browser/WebGL behavior, cross-origin policy, and output size all affect results. Keep a small diagnostic page in your test suite.
  • Reproducibility: record browser, operating system, viewport, device scale, Mapbox GL JS version, html2canvas version, style, and capture dimensions with each failure.
  • Output: PNG preserves lossless map text and lines; if you need a composed page, keep the html2canvas route but validate every remote asset and target browser.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One request can return PNG, JPEG, WebP, or PDF without you managing a browser session. Before capture it accepts the cookie/consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

For a public map page, the one-call version is:

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

See the ScreenshotNeo documentation for all options, including viewport and device presets, retina scale, full-page and element capture, custom CSS or JavaScript, click and wait conditions, request blocking, headers, cookies, user agent, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture, usage, and OpenAPI access.

Python

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)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account.

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

FAQ

Does preserveDrawingBuffer: true fix every black html2canvas image?

No. It enables Mapbox’s documented canvas export path. html2canvas still reconstructs the DOM, so its output can fail for independent reasons.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Should I always use html2canvas for a Mapbox map?

No. Use direct Mapbox canvas export when the map alone is needed; use html2canvas when you need a composed DOM region and have tested its limitations.

Is waiting a fixed number of milliseconds reliable?

No. A fixed delay can hide a race on one machine and fail on another. Prefer an application readiness signal and use idle as a practical diagnostic checkpoint.

Frequently Asked Questions

Can I enable preserveDrawingBuffer after the map has loaded?

Construct the map with the option from the beginning; changing it after the WebGL context exists is not the documented export workflow.

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

Why does a screenshot fail only on one browser or device?

WebGL implementations, canvas allocation limits, hardware acceleration, and cross-origin behavior vary by browser and platform. Reproduce with the same runtime, viewport, and scale used in production.

The Bottom Line

Prove the Mapbox canvas can export first: construct it with preserveDrawingBuffer: true, wait for rendering to settle, and test map.getCanvas().toDataURL(). If that succeeds while html2canvas remains black, debug html2canvas’s reconstruction, cross-origin resources, dimensions, and browser runtime as a separate problem.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.