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 DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
CORS

How to Capture a Leaflet Map with html2canvas

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

To export a Leaflet map with html2canvas, give the map container a real height, configure its tile layer for cross-origin access when the provider supports it, wait for tiles and overlays to finish loading, then render the map element and download the canvas as a PNG. The important limitation: html2canvas rebuilds an image from DOM properties; it does not take a literal browser screenshot. Tiles without compatible CORS headers can therefore appear blank or make the canvas unreadable.

What you need before capturing

  • A Leaflet map inside an element with non-zero width and height. A fixed CSS height is the simplest choice.
  • html2canvas loaded on the page and a map element you can select.
  • A tile provider whose usage terms permit your use and whose server supports the cross-origin access needed for exporting pixels.
  • A capture triggered only after the map tiles and any overlays have loaded.

Leaflet provides the interactive map library, not the underlying map imagery. Choose a tile provider separately, retain its required attribution, and follow its production and usage policy. Leaflet lists providers including Mapbox, Bing Maps, Esri ArcGIS, HERE Maps, and Stadia Maps; their availability, terms, and CORS behavior are provider-specific. See Leaflet and its quick start.

Give the map a defined size

Leaflet needs a visible container to lay out the map. Set its height explicitly and ensure its width is not zero or hidden when you initialize or capture it.

#map {
  width: 100%;
  height: 480px;
}

If the map is in a tab, modal, or other initially hidden region, reveal it and let Leaflet recalculate its size before capturing. A zero-size or stale layout can yield an empty or clipped image even when the tile requests succeed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
ChaoQ Stylus Pen for Touchscreen, 3pcs Stylus Pen for iPad iPhone Android
  • Stylus Pen for Touchscreen: No Bluetooth or charging needed—use instantly on any capacitive touch screen (iPad, iPhone, Android, Samsung). Dual rubber tips (5mm/6.6mm) ensure precise control for writing, drawing, or gaming. Lightweight aluminum body with vibrant colors.
  • Precision & Comfort Redefined: High sensitivity rubber tip glides smoothly without lag or scratches. Ergonomic design reduces wrist strain for extended use. Compatible with tablets, phones, and Laptops.
  • Dual-Tip Flexibility: Switch between 0.20” and 0.26” rubber nibs for detailed art or bold notes. Anti-scratch, fingerprint-resistant tip. Pretty bright metal colors inspire creativity.
  • Effortless Multi-Device Compatibility: Works seamlessly on Apple, Samsung, Android, and more. No apps or setup—just pick up and write. Perfect for notes, games, or gifts—ready to spark ideas instantly. Replaceable tips included for long-term use.
  • Creative Freedom, Anywhere: Lightweight aluminum stylus with natural grip. Includes 6 replaceable tips and 3 color stylus pens. Perfect for sharing with friends, family, or colleagues, this bundle ensures you’re always equipped to capture inspiration.

Set up Leaflet and html2canvas

The example below assumes Leaflet and html2canvas are already loaded, a tile URL and attribution appropriate to your provider, and a page containing <div id="map"></div>. Keep the provider attribution visible in the map or include it in the final output as required by the provider. Do not treat a public demo tile endpoint as unrestricted production hosting.

const map = L.map('map').setView([51.505, -0.09], 13);

const tiles = L.tileLayer('YOUR_TILE_PROVIDER_URL', {
  attribution: 'YOUR_PROVIDER_ATTRIBUTION',
  crossOrigin: true
}).addTo(map);

Replace the URL and attribution with the values specified by your tile provider. Leaflet’s TileLayer reference describes crossOrigin as an option for accessing tile pixel data. Some providers require a particular string or request configuration rather than simply true; use the provider’s documented value. A provider may also require a referrerPolicy for token or referrer validation.

Wait for map content, then download a PNG

Call html2canvas only once the base tiles and any asynchronous overlays you depend on have completed. The following helper waits for Leaflet’s currently loading tiles, then captures the map. If your application adds overlays or changes layers asynchronously, include those operations in the readiness logic too.

Rank #2
Sale
Stylus (7 Pcs), 2-in-1 Stylus Pen for Touch Screen, High Precision and Sensitivity, Suitable for iPad/iPhone/Samsung/Android Smartphone and Tablets, Compatible with All Touch Screen (Multicolor)
  • 【Stylus Pen for Touchscreen】Our stylus pen requires no Bluetooth pairing or charging, you can unleash your creativity anytime and anywhere, just pick up the stylus and express your thoughts freely on the touchscreen.
  • 【2-in-1 Stylus Pen】: Tablet stylus for touchscreen, made of lightweight alloy, no need for Bluetooth connection or charging, ready to use after opening the package, comfortable in hand, sturdy, durable and anti-aging, so you can use it anytime, anywhere Easily capture inspiration and make everything feel like writing on paper, giving you a more accurate writing/drawing/touching experience.
  • 【High Sensitivity & Precision】Acempire stylus can flexibly fit on the screen without delays, interruptions, or screen scratches, allowing you to have a smoother writing or drawing experience and enhance your creative pleasure.
  • 【Compatibility and multi-purpose】: Universal stylus, suitable for touchscreen devices (for nintendo switch stylus, for switch 2 stylus, Apple, Samsung, Moto, Lenovo, Xiaomi, etc., and also compatible with major operating systems, such as: Google, Android, Microsoft, etc.), you can use it like a real pen, You can use our stylus to write on drawing applications, take notes, read news, play games, etc. just like any other touchscreen device.
  • 【Professional customer service】: we provide professional 24-hour customer service. If you encounter any product problems, please feel free to contact us through the store, and you will get a solution in the shortest time.
function waitForTiles(layer) {
  return new Promise((resolve) => {
    // If all tiles are already loaded, there may be no pending load event.
    if (layer._loading !== true) {
      resolve();
      return;
    }
    layer.once('load', resolve);
  });
}

async function downloadLeafletMap() {
  const mapEl = document.querySelector('#map');
  if (!mapEl || mapEl.clientWidth === 0 || mapEl.clientHeight === 0) {
    throw new Error('Map element is missing or has no visible dimensions.');
  }

  await waitForTiles(tiles);

  const canvas = await html2canvas(mapEl, {
    useCORS: true,
    backgroundColor: null,
    scale: window.devicePixelRatio,
    logging: false
  });

  const link = document.createElement('a');
  link.download = 'leaflet-map.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}

downloadLeafletMap().catch(console.error);

The helper checks Leaflet’s internal _loading property to handle the case where loading has already finished. Because that property is internal, adapt the readiness check to your application if you need a stable, application-level guarantee: for example, track the tile layer’s loading and load events from the moment it is added, and separately await data-backed overlays. The core export pattern uses the html2canvas Promise and canvas.toDataURL().

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

useCORS: true asks html2canvas to load images through CORS where supported; it cannot grant permission the tile server has not sent. backgroundColor: null preserves transparency where the rendered content permits it. scale: window.devicePixelRatio creates a higher-resolution output on high-density displays, but increases memory use and can run into browser canvas-size limits. Set logging: false to silence html2canvas logging.

Crop the output or set its dimensions

html2canvas supports crop coordinates and dimensions through x, y, width, and height. Set them when you need a defined portion or output size rather than relying on the viewport or the map element’s natural dimensions.

Rank #3
Bopomofo Stylus(5 Pcs),2-in-1 Stylus Pen for Touchscreen,Capacitive Stylus
  • 【Stylus for Touch Screen】This stylus can be used on touch screen, designed to replace your fingers, the stylus can free up your fingers and provide higher sensitivity and response on the screen.
  • 【Capacitive stylus】This is a capacitive stylus (battery-free, requires no charging, and functions like a fingertip)—not an active stylus. It does not support pressure sensitivity or palm rejection. However, it allows for tapping, scrolling, note-taking, and drawing on touchscreens; if you require professional-grade drawing capabilities on an iPad, please choose an active stylus instead.
  • 【2-in-1 Stylus Pen】This stylus features two different tips: a flexible transparent disc tip and a rubber tip. Applying moderate pressure when using the rubber tip ensures full contact with the screen—especially on screens with protective films—thereby enabling stable signal transmission. The combination of the rubber tip and the disc tip offers two distinct touch experiences.Please note that the plastic piece on the transparent disc is an integral part of the tip and cannot be removed.
  • 【Works On Capacitive Touch Screens】Compatible with iPad, iPad Air/mini, iPhone, Samsung Galaxy Tab, Android tablets, Kindle and smartphones. Also works over most screen protectors — glide, no scratch. The stylus is used to replace your fingers on a touchscreen, Avoid rubbing your fingers and leaving fingerprints on touchscreen devices. If it cannot be used for writing on some devices, This may be due to limitations in the settings of touchscreen devices. If you cannot find a solution, please contact us at any time, and we will help you resolve the issue.
  • 【Multiple Usage Scenarios】Whether you are taking notes in class, reviewing documents at work, drawing creative designs, or enjoying mobile games, this universal stylus pen delivers a smooth and comfortable touch experience. It is ideal for writing, sketching, annotating, scrolling, and precise screen control on tablets and smartphones. From daily tasks to creative projects, this stylus helps you capture ideas anytime and anywhere.
const canvas = await html2canvas(mapEl, {
  useCORS: true,
  x: 0,
  y: 0,
  width: 800,
  height: 500,
  scale: 1
});

The values are capture coordinates and dimensions; choose them to match the intended region and confirm the resulting canvas dimensions before using it downstream. html2canvas’s configuration reference documents these and other options.

Exclude controls or other page elements

To omit Leaflet controls or decorations from a clean map export, mark them with data-html2canvas-ignore where appropriate, or use the ignoreElements configuration callback. These options remove selected DOM elements from the html2canvas render; they do not fix a tile’s CORS restrictions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await html2canvas(mapEl, {
  useCORS: true,
  ignoreElements: (element) => element.classList.contains('export-ignore')
});

Why tiles are missing or the canvas cannot be downloaded

The most common cause is cross-origin access. Browsers restrict reading pixels from images loaded from another origin unless that server grants access with a compatible Access-Control-Allow-Origin response header. If a tile server does not provide the required header, html2canvas cannot make the tile readable by setting useCORS alone. The browser may omit the tile, or the canvas may become tainted and reject toDataURL().

Rank #4
3PCS Tablets Stylus Pen for All Touchscreen Devices with Precision Disc Tip
  • Wide Compatibility for Multiple Devices: Works seamlessly with Samsung, iOS, Android, Chromebook, Smartphone, and other touchscreen devices. No drivers are needed- simply open and play, ensuring compatibility with a variety of tablets and smartphones. No Charging Required, Ready Anytime.
  • High-Precision Touch for Smooth Writing & Drawing: Featuring advanced capacitive technology, this stylus pen offers high sensitivity and precision, delivering a smooth, real-pen experience perfect for writing, sketching, note-taking, and more.
  • Ergonomic Design for Comfortable Grip: Crafted with a lightweight and durable body, the stylus is designed for long periods of comfortable use. Whether you’re creating, studying, or performing everyday tasks, it ensures a pleasant grip.
  • Scratch-Resistant & Durable, Protects Your Screen: Equipped with a soft, high-quality Disc tip that ensures smooth touch without scratching the screen, keeping your device’s display in pristine condition while providing a seamless user experience.
  • A great gift: Get 3 different colors of styluses at an unbeatable price instead of a high-priced pencil. You can share these stylus pens with your friends or family.

Leaflet’s crossOrigin option and html2canvas’s useCORS address different parts of the path: Leaflet configures tile image requests for pixel access, while html2canvas attempts CORS-aware loading when it reconstructs the DOM. Neither overrides the server’s policy. The html2canvas FAQ explains the tainted-canvas restriction and possible proxy approach at its FAQ.

What html2canvas can and cannot reproduce

html2canvas reconstructs a picture from DOM information instead of taking a browser screenshot. Unsupported CSS, cross-origin iframes, and already-tainted canvases may be missing or unreadable; its supported-features documentation is at html2canvas features.

Leaflet’s HTML controls and HTML-based L.divIcon content are not rasterized by the separate leaflet-image exporter. For vector layers that must appear in an export, Leaflet can render vectors to Canvas with renderer: L.canvas() or preferCanvas: true where appropriate. This does not make arbitrary HTML controls part of a canvas-rendered vector layer. See the leaflet-image documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Stylus Pens for Touch Screens, 2 in 1 High Precision Universal Stylus Pen for iPad Compatible with Apple, iPhone, iPad, Android, Microsoft Tablets, Phones, 3 Pack - Blue, Pink, Purple
  • 【PREPARE YOUR IPAD BEFORE USE】Before using our iPad pen, ensure the "Only Draw with Apple Pencil" feature is off in Settings > Apple Pencil. Disabling this option is crucial for proper stylus functionality.
  • 【UNIVERSAL STYLUS】Our stylus pens for touch screens are widely compatible with all touch screens including smartphones, Android tablets, touch screen laptops/PCs. They also work with Apple iPads, iPhones, iPad Pro, iPad Mini, iPad Air, Surface, Chromebooks and other capacitive touch screen devices.
  • 【2-in-1 DESIGN】The stylus pen comes with different tips on both ends. One end is the disc tip, which is more accurate and sensitive, suitable for taking notes and drawing. The other end is a durable fibre tip for browsing or scrolling web pages, effectively protecting the screen from fingerprints or smudges.
  • 【HIDDEN SPARE TIP】This 3 pack of stylus pens includes 3 additional disc tips and 3 extra fibre tips. Each disc tip is placed inside the stylus body. The spare tip can be taken out by simply rotating the fibre tip end. Convenient for always having a spare pen tip ready to go.
  • 【HIGH PRECISION & SENSITIVITY】The stylus pen features a flexible disc tip that fits flexibly on the screen without leaving broken lines. Additionally, the disc tip is transparent, allowing you to get a clearer view when writing or drawing.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

Symptom Likely cause What to check or change
Tiles are blank or missing Capture started before tiles loaded, the tile request failed, or the provider does not grant compatible CORS access. Wait for the layer’s load event; inspect browser Network and Console panels; verify tile responses include the required CORS header. If not, use a provider that supports the needed access or a properly authorized same-origin proxy.
toDataURL() throws a security error A cross-origin image tainted the canvas. Fix the tile server CORS path or proxy the image through a server you control and are permitted to use. allowTaint does not make a tainted canvas safely readable.
Map is empty or clipped The element has zero dimensions, is hidden, or the capture viewport does not match its scroll dimensions. Confirm non-zero width and height, make the map visible, call Leaflet’s size update after revealing it, and align windowWidth and windowHeight with the element’s scroll dimensions where needed.
Markers or custom overlays are absent The overlay was not ready, uses unsupported DOM or CSS, or is an HTML-based icon not handled by a canvas exporter. Wait for overlay data and rendering; inspect whether it is DOM, SVG, or canvas; use Canvas rendering for vector layers that must be exported, or retain html2canvas for supported DOM elements.
Image is soft, oversized, or capture fails on a large map High device-pixel scale creates a large bitmap that exceeds browser canvas or memory limits. Reduce scale, crop to the required region, or lower output dimensions. Browser canvas limits vary, so there is no single safe maximum for every browser and device.
Tiles fail when an API key or referrer is involved The provider validates the request origin, token, or referrer policy. Check the provider’s browser integration instructions and configure Leaflet’s referrerPolicy only as that provider requires; do not expose a secret key in client code.

When to use a proxy or a different renderer

If the chosen tile provider does not grant browser-readable CORS access, a same-origin proxy can fetch tiles and return them under your origin, but use it only when your provider’s terms permit that delivery pattern. A proxy adds server work, latency, and responsibility for access controls; avoid creating an unrestricted endpoint that anyone can use to fetch arbitrary URLs. Alternatively, choose a tile source whose policy and CORS behavior fit the export use case.

If the requirement is a literal browser-rendered screenshot rather than a reconstructed DOM image, or the page includes content html2canvas cannot reproduce, use a browser-based screenshot approach or server-side renderer instead. The right choice depends on whether you need the live browser’s actual painted result, pixel-readable tiles, reliable automation, or simply a client-side export of supported map DOM.

Or skip the browser setup

For a server-side screenshot of a rendered map page, ScreenshotNeo provides a website screenshot API. It is not a replacement for the Leaflet CORS rules when you are exporting a client-side canvas; it is an alternative when you want a rendered page capture without wiring html2canvas into the browser. One GET request can return PNG, JPEG, WebP, or PDF. See the ScreenshotNeo site and API documentation.

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

Replace the example URL with a publicly accessible page containing your map and supply your API key. ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, and cache hits are not billed. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

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

Sign up for ScreenshotNeo free: 1,000 screenshots a month, no card required.

Frequently Asked Questions

Can I save a Leaflet map as JPEG or WebP with html2canvas?

Yes. Convert the canvas with canvas.toDataURL('image/jpeg') or canvas.toDataURL('image/webp') in browsers that support the requested format, and use a matching filename extension.

Does html2canvas capture map attribution automatically?

It renders eligible DOM content inside the selected element, so visible attribution may appear in the image. Check the tile provider’s terms and ensure attribution remains legible and present in any exported or redistributed image.

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.

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

Leave a Reply

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

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.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.