How to Capture Leaflet Maps with html2canvas
Capture Leaflet maps as PNGs with html2canvas, fix missing tiles and CORS, export overlays correctly, and compare browser capture with ScreenshotNeo.

Direct answer: Give the Leaflet map container a real CSS height, configure the tile layer for cross-origin pixel access, wait until tiles and overlays finish loading, then call html2canvas with useCORS: true. Export the returned canvas with toDataURL('image/png'). Missing tiles usually mean that the tile server does not send a compatible CORS header, the capture ran before tiles loaded, or the map element has no usable dimensions.
This method works well for a client-side download or a quick preview. It reconstructs the map from DOM elements and images; it is not a literal browser screenshot. Unsupported CSS, cross-origin iframes and tainted canvases can be missing or unreadable. For production jobs, repeatable server-side captures, or pages with consent banners and popups, see the ScreenshotNeo option after the browser implementation.
1. Create a map container with a fixed height
Leaflet needs a non-zero width and height before it can lay out tiles. A missing height is one of the most common reasons for an empty export. The official quick start uses a dedicated map element with an explicit height; follow the same pattern in your stylesheet.
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'>
<style>
#map {
width: 100%;
height: 480px;
}
</style>
</head>
<body>
<div id='map'></div>
<script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'></script>
</body>
</html>
Do not rely on height: 100% unless every parent has a defined height. Check the element in DevTools: mapEl.getBoundingClientRect() should report a positive width and height.
2. Add Leaflet tiles, attribution and overlays
Use a tile provider whose terms permit your use case. Keep the provider’s attribution visible in the interactive map and in any exported image where its policy requires it. Leaflet provides the map library, not the imagery; its documentation lists providers such as Mapbox, Bing Maps, Esri ArcGIS, HERE Maps and Stadia Maps. Read the selected provider’s rate limits, token rules, attribution requirements and production policy before deploying.

const map = L.map('map', {
center: [51.505, -0.09],
zoom: 13
});
const tiles = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
maxZoom: 19,
crossOrigin: true,
attribution: '© OpenStreetMap contributors'
}
).addTo(map);
const marker = L.marker([51.505, -0.09])
.addTo(map)
.bindPopup('A Leaflet marker');
L.polyline([
[51.505, -0.09],
[51.51, -0.1],
[51.515, -0.08]
], { color: '#2563eb', weight: 4 }).addTo(map);
The crossOrigin TileLayer option tells Leaflet to request tiles in a way that permits pixel access when the provider supports it. The image response must also include a compatible Access-Control-Allow-Origin header. Some providers require a particular crossOrigin value or a referrerPolicy because they validate tokens or referrers; follow that provider’s instructions and the Leaflet TileLayer reference.
3. Wait for tiles and overlays before capturing
An immediate call to html2canvas can catch an empty tile grid or partially drawn overlays. Wait for the TileLayer’s load event, and give your own markers, popups or canvas-rendered layers time to finish. For several layers, count their load events or wait for each one explicitly.
function waitForTileLayer(layer) {
return new Promise(resolve => {
if (layer._tilesToLoad === 0) {
resolve();
return;
}
layer.once('load', resolve);
});
}
await waitForTileLayer(tiles);
map.invalidateSize();
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
// If you open a popup or add an animation, wait until it is visible.
marker.openPopup();
await new Promise(resolve => setTimeout(resolve, 250));
The private _tilesToLoad check is convenient but can vary between Leaflet versions. In a stricter application, attach your own load listener before adding the layer and resolve it from that event. A short animation-frame delay lets layout and painting settle; it does not repair a server-side CORS problem.
4. Capture the map with html2canvas
Install or load html2canvas, select the map element, and export the resolved canvas. The library’s documentation explains that it builds a representation from DOM properties rather than taking a literal browser screenshot. Its configuration options include CORS handling, scale, background color, cropping and element filtering.
<script src='https://html2canvas.hertzen.com/dist/html2canvas.min.js'></script>
<script>
async function downloadLeafletMap() {
const mapEl = document.querySelector('#map');
const canvas = await html2canvas(mapEl, {
useCORS: true,
backgroundColor: null,
scale: window.devicePixelRatio,
logging: false,
ignoreElements: element => element.matches('.leaflet-control-attribution')
});
const link = document.createElement('a');
link.download = 'leaflet-map.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
document.querySelector('#download').addEventListener('click', downloadLeafletMap);
</script>
If attribution must remain in the output, remove the ignoreElements function. You can also mark individual controls with data-html2canvas-ignore. The html2canvas configuration reference documents useCORS, scale, backgroundColor, ignoreElements, x, y, width and height.
5. Crop or set a fixed output size
To capture only part of the map, pass coordinates relative to the document or element and specify the output dimensions. For a stable image size, do not depend on whatever viewport happens to be open on the user’s device.
const rect = mapEl.getBoundingClientRect();
const canvas = await html2canvas(mapEl, {
useCORS: true,
x: 40,
y: 20,
width: Math.min(800, rect.width - 80),
height: Math.min(500, rect.height - 40),
scale: 2,
windowWidth: mapEl.scrollWidth,
windowHeight: mapEl.scrollHeight
});
For a full-page map element, match windowWidth and windowHeight to its scroll dimensions. If the output is clipped or the browser throws a canvas-size error, lower scale, reduce the map dimensions, or capture tiles in smaller regions.
6. Make vector layers export reliably
Leaflet paths can use SVG or Canvas renderers. If a vector layer must appear consistently in an export, use Canvas rendering for that layer or set preferCanvas: true when appropriate.
const map = L.map('map', {
center: [51.505, -0.09],
zoom: 13,
preferCanvas: true
});
L.circle([51.508, -0.11], {
renderer: L.canvas(),
radius: 250,
color: '#dc2626'
}).addTo(map);
HTML controls and HTML-based L.divIcon content are not guaranteed to be rasterized by related Leaflet image exporters. html2canvas can reproduce ordinary DOM content, but complex CSS, transformed elements and cross-origin content still have limits. Test the exact marker and popup styles you use.
7. Why Leaflet tiles are missing
| Symptom | Likely cause | Fix |
|---|---|---|
| All tiles are blank | The map has zero height or capture ran too early. | Set a concrete CSS height, call invalidateSize(), and wait for the tile load event. |
Tiles display, but toDataURL throws a security error |
A cross-origin tile tainted the canvas. | Use crossOrigin and useCORS only with a provider that sends Access-Control-Allow-Origin. Otherwise use a same-origin proxy or another permitted provider. |
| Some tiles are missing | Capture started while requests were still pending, or a tile request failed. | Inspect Network responses, wait for all layers, and handle failed or rate-limited requests. |
| Markers or paths are absent | The layer is animated, outside the element, or uses unsupported rendering. | Wait for animation, call fitBounds before capture, and try Canvas rendering for vectors. |
| Controls clutter the image | Leaflet controls are descendants of the map element. | Use data-html2canvas-ignore or ignoreElements, while retaining required attribution. |
| Output is blurry | The canvas is rendered at CSS resolution. | Set scale: window.devicePixelRatio or a controlled value such as 2, within browser canvas limits. |
| Output is clipped or empty | Viewport dimensions do not match the scrollable element. | Set windowWidth/windowHeight from the element, and reduce the capture size if necessary. |
allowTaint: true is not a universal solution. It permits a tainted canvas to exist, but browser security still prevents safely reading it with toDataURL or pixel APIs. The server response headers are the deciding factor.
8. Browser limits and production considerations
CORS and proxies
You cannot add a missing CORS header from browser JavaScript. A same-origin image proxy can fetch tiles and add an appropriate header, but it becomes your responsibility to respect the tile provider’s terms, protect credentials, cache safely and control abuse. Do not expose private map tokens in a client-side bundle.

Canvas size and memory
A retina scale multiplies both dimensions and memory. A 2,000 by 1,000 CSS-pixel map at scale 3 becomes a 6,000 by 3,000 bitmap. Mobile browsers may fail before desktop browsers do. Set a maximum export size, lower the scale for very large maps, and release temporary canvases after downloading.
Repeatability
Tile availability, network timing, fonts and provider rate limits can change between captures. For deterministic jobs, wait for network completion, use fixed map bounds and zoom, disable animations, and record the tile provider and capture settings alongside the output.
Or skip the browser setup
When you need a clean screenshot of a rendered map page rather than a canvas assembled in the user’s browser, ScreenshotNeo’s API accepts one GET request and returns PNG, JPEG, WebP or PDF. It can wait for a selector, delay or network idle; load lazy images; set a viewport or device preset; run custom JavaScript; hide selectors; set cookies and headers; and capture one element by CSS selector.
curl -G 'https://api.screenshotneo.com/v1/shot' \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://your-site.example/map \
-o shot.webp
import requests
r = requests.get(
'https://api.screenshotneo.com/v1/shot',
params={'access_key': 'YOUR_API_KEY', 'url': 'https://your-site.example/map'},
timeout=90
)
r.raise_for_status()
open('shot.webp', 'wb').write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://your-site.example/map' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.arrayBuffer();
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', Buffer.from(data)));
Cookie banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts and cache hits are not billed, and response headers identify the page verdict and billing status. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Performance, reliability and cost checklist
- Use a fixed map size and wait for every required layer.
- Keep tile attribution and follow the imagery provider’s usage policy.
- Use CORS-compatible tiles or a permitted same-origin proxy.
- Disable animations and set deterministic bounds for repeatable exports.
- Choose a scale that fits browser canvas and memory limits.
- Ignore controls only when doing so does not remove required attribution.
- For batch, server-side or authenticated captures, use a renderer designed for API jobs and monitor response status.
FAQ
Can html2canvas capture a Leaflet map without a proxy?
Yes, when every tile and image is served with compatible CORS headers and you configure the tile layer and html2canvas accordingly. Otherwise the canvas may be tainted or unreadable.
Why does the map look correct on screen but export blank?
The browser can display cross-origin images without granting JavaScript pixel access. The export also may have started before tiles loaded. Check response headers and wait for the TileLayer’s load event.
Should I use SVG or Canvas for Leaflet paths?
Both can work, but Canvas rendering is often easier to control for image export. Set preferCanvas or provide L.canvas() to the layer, then capture after rendering completes.
Can I export a PDF directly with html2canvas?
html2canvas returns a canvas. You need a separate PDF library or server workflow to place that bitmap in a PDF. A screenshot API with PDF output can handle that format directly.
How do I capture just the map and not the page controls?
Pass the map element itself to html2canvas and filter unwanted descendants with ignoreElements or data-html2canvas-ignore. Preserve any attribution required by the tile provider.


