How to Capture Leaflet Polygons With html2canvas or Save a Leaflet Map as PNG
Capture Leaflet polygons and tiles as a PNG with html2canvas, fix CORS and blank exports, or automate map screenshots with ScreenshotNeo.

Direct answer: wait until Leaflet has rendered its tiles and polygon paths, then capture the map element with html2canvas. Use useCORS: true, set an explicit canvas scale, convert the result with canvas.toDataURL('image/png'), and trigger a download. If any tile or image lacks CORS permission, use a same-origin proxy or a provider that sends Access-Control-Allow-Origin. For automated server-side captures, you can skip browser setup with ScreenshotNeo.
1. Capture the map with html2canvas
This complete example creates a Leaflet map, adds a polygon, waits for the map to become visible, and downloads the visible map composition as a PNG. It includes controls and other HTML inside the map container unless you explicitly hide them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Leaflet PNG export</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
#map { width: 100%; height: 480px; }
.export-controls { margin: 12px 0; }
</style>
</head>
<body>
<div class="export-controls" data-html2canvas-ignore="true">
<button id="save-map" type="button">Save PNG</button>
</div>
<div id="map"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
crossOrigin: true,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047],
[51.515, -0.06]
], {
color: '#2563eb',
fillColor: '#60a5fa',
fillOpacity: 0.45,
weight: 3
}).addTo(map);
map.fitBounds(polygon.getBounds());
function waitForImages(root) {
const images = Array.from(root.querySelectorAll('img'));
return Promise.all(images.map((image) => {
if (image.complete) return Promise.resolve();
return new Promise((resolve) => {
image.addEventListener('load', resolve, { once: true });
image.addEventListener('error', resolve, { once: true });
});
}));
}
async function saveLeafletPng() {
const mapElement = document.getElementById('map');
await waitForImages(mapElement);
await new Promise((resolve) => map.whenReady(resolve));
await new Promise((resolve) => setTimeout(resolve, 300));
const canvas = await html2canvas(mapElement, {
useCORS: true,
backgroundColor: '#fff',
scale: window.devicePixelRatio || 1,
logging: false
});
const link = document.createElement('a');
link.download = 'leaflet-map.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
document.getElementById('save-map').addEventListener('click', saveLeafletPng);
</script>
</body>
</html>
The html2canvas examples use the same canvas-to-data-URL download pattern. The map container needs a nonzero height; Leaflet’s quick start demonstrates this requirement.
2. Make polygons and tiles export reliably
Give the container a real size
A zero-height or hidden map produces a blank or cropped image. Set height in CSS and capture only after the map is displayed. If the map is inside a hidden tab or modal, open it first and call map.invalidateSize() before capturing.

Wait for tiles and overlays
map.whenReady() means Leaflet has initialized; it does not guarantee every raster tile has finished loading. Wait for the tile layer’s load event, wait for image elements, or use a short delay after the final view change.
const tiles = L.tileLayer(tileUrl, { crossOrigin: true }).addTo(map);
await new Promise((resolve) => tiles.once('load', resolve));
map.invalidateSize();
const canvas = await html2canvas(document.querySelector('#map'), {
useCORS: true,
scale: window.devicePixelRatio || 1
});
Render polygons with Canvas when using leaflet-image
For the leaflet-image route, use Leaflet’s Canvas renderer for vector layers or set preferCanvas: true on the map. SVG paths can otherwise be omitted by the layer renderer.
const map = L.map('map', { preferCanvas: true });
const polygon = L.polygon(coordinates, {
renderer: L.canvas(),
color: '#2563eb',
fillOpacity: 0.45
}).addTo(map);
3. Understand CORS and tainted canvases
Browsers prevent JavaScript from reading pixels from cross-origin images unless the image server grants permission. useCORS: true tells html2canvas to request images with CORS, but it cannot create permission that the tile server does not send. The html2canvas documentation describes both useCORS and the proxy option.

Configure every raster source: basemap tiles, image overlays, custom marker images, and any background images. Leaflet’s tile-layer crossOrigin option must be set before tiles load. One image without compatible headers can taint the canvas and make toDataURL() throw a security error.
| Symptom | Likely cause | Fix |
|---|---|---|
| Tiles are missing | Tile server does not allow CORS | Use a CORS-capable provider, a same-origin proxy, and useCORS: true. |
SecurityError from toDataURL() |
The canvas is tainted by one cross-origin image | Fix CORS for every raster source or remove the offending layer. |
| Export works without tiles | Polygon is local but basemap is cross-origin | Test each layer separately and configure the basemap’s crossOrigin. |
A proxy must fetch the image and serve it from your origin with suitable headers. Do not proxy arbitrary URLs without access controls; proxy only the tile and image hosts your application is allowed to use.
4. Use leaflet-image when you need map layers only
leaflet-image composes Leaflet layers into a canvas without reconstructing the surrounding DOM. It is useful when you want the basemap and vector layers, but it does not include HTML controls, legends, popups, or L.divIcon content. Its README also requires CORS-capable tiles and markers.
<script src="https://unpkg.com/leaflet-image@0.4.0/leaflet-image.js"></script>
<script>
function saveLayersOnly() {
leafletImage(map, function (error, canvas) {
if (error) {
console.error(error);
return;
}
const link = document.createElement('a');
link.download = 'leaflet-layers.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
}
</script>
Keep attribution in the exported image when your tile provider requires it. Generated map images generally need the same attribution as the interactive map.
5. Choose the right capture method
| Requirement | html2canvas | leaflet-image | Static image service |
|---|---|---|---|
| Include controls and surrounding HTML | Yes, subject to DOM and CSS support | No | Usually no interactive DOM |
| Include polygons | Yes, when the rendered paths are visible | Yes, most reliably with Canvas rendering | Depends on the service’s overlay format |
| Run in the browser | Yes | Yes | Usually server-side |
| Cross-origin requirements | Every raster source must be CORS-compatible | Tiles and markers must be CORS-compatible | Provider fetches sources according to its own rules |
| Best fit | Visible page composition | Leaflet layers only | Repeatable automated exports |
html2canvas reconstructs the DOM rather than taking a pixel-perfect browser screenshot, so unsupported CSS, fonts, animations, and cross-origin assets can differ from what a user sees. A static-map API can be simpler and faster for repeatable exports; the leaflet-image documentation points to the Mapbox Static Image API as one example.
6. Options for cropping, quality, and exclusions
Capture one element or the full map
Pass the exact map element to html2canvas. Capturing document.body adds unrelated content and increases canvas dimensions. To capture a larger scrollable composition, provide explicit windowWidth and windowHeight, but remember that the output is still constrained by browser canvas-size limits.
const canvas = await html2canvas(document.querySelector('#map'), {
useCORS: true,
windowWidth: document.documentElement.scrollWidth,
windowHeight: document.documentElement.scrollHeight,
scale: 2,
backgroundColor: '#ffffff'
});
Hide controls and transient elements
Add data-html2canvas-ignore="true" to a control, or remove it before capture. You can also pass an ignoreElements function for conditional filtering.
const canvas = await html2canvas(mapElement, {
useCORS: true,
ignoreElements: (element) => element.matches('.zoom-buttons, .export-button')
});
Improve sharpness without exceeding limits
scale: window.devicePixelRatio preserves high-DPI detail. A fixed value such as 2 gives predictable output, but larger values multiply memory use and can hit browser canvas limits. Reduce the map dimensions or scale when exports fail on large screens.
7. Common errors and fixes
| Error or result | Cause | Fix |
|---|---|---|
| Blank PNG | The map has not been laid out, is hidden, or has zero height | Display it, set an explicit height, call invalidateSize(), then capture. |
| Polygon missing | Capture ran before the layer was added or the renderer was unsuitable | Await layer creation and use L.canvas() or preferCanvas for leaflet-image. |
| Only part of the map appears | The target element or viewport dimensions are too small | Capture #map itself and set appropriate windowWidth/windowHeight. |
| Controls appear in the file | They are normal DOM children of the map | Add data-html2canvas-ignore or use ignoreElements. |
| Fonts or icons differ | Fonts or external assets were not loaded or are unsupported | Wait for fonts and images, use same-origin assets, and verify the font is available before capture. |
| Animations produce inconsistent frames | The map or overlay changed during rendering | Pause animations and wait for the final view before invoking html2canvas. |
| Download does nothing | Browser blocked a synthetic click or the canvas conversion failed | Call the function from a user gesture, inspect console errors, and verify CORS. |
| Browser freezes or throws a canvas-size error | Output dimensions and scale are too large | Lower scale, reduce the capture area, or export in tiles/pages. |
8. Performance, reliability, and licensing considerations
- Performance: html2canvas walks and paints the DOM, so a smaller target and fewer visible layers render faster. Large
scalevalues increase memory use roughly with the number of output pixels. - Reliability: wait for tile and overlay completion, freeze animations, and retry only after diagnosing failed resources. A retry cannot fix a persistent CORS policy.
- Data freshness: capture after the final
setView,fitBounds, or layer update. Calling capture immediately after a map change can produce an older frame. - Attribution: preserve required provider attribution in the image or adjacent export UI. Check the terms for every tile, marker, and overlay source.
- Cost: browser-side html2canvas and leaflet-image have no API request charge, but they consume the user’s CPU, memory, and bandwidth. A server-side service trades local setup for service usage and operational controls.
9. Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. One GET request captures a rendered page as PNG, JPEG, WebP, or PDF. The API can capture a map page after it loads, and its options include full-page capture with lazy images loaded, custom viewport and device presets, retina scale, custom CSS or JavaScript, click and wait conditions, request blocking, custom headers, cookies, user agents, timezone, geolocation, caching, async jobs, bulk capture, and signed webhooks. See the ScreenshotNeo API documentation for parameter details.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://your.example.com/leaflet-map \
-o leaflet-map.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={
"access_key": "YOUR_API_KEY",
"url": "https://your.example.com/leaflet-map"
},
timeout=90,
)
r.raise_for_status()
open("leaflet-map.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://your.example.com/leaflet-map'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('leaflet-map.webp', image);
Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing status. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
10. FAQ
Can html2canvas capture a Leaflet popup?
Yes, if the popup is visible inside the element being captured and its assets satisfy browser CORS rules. Hide it with an ignore selector when it should not appear.
Why does leaflet-image omit my legend?
Legends and controls are HTML, while leaflet-image focuses on Leaflet layers. Use html2canvas for the complete DOM composition.
Should I use PNG or JPEG?
PNG preserves sharp polygon edges and transparency-free map labels. JPEG can produce smaller files when minor compression artifacts are acceptable.
Can I export a map without exposing tile URLs to the browser?
Use a server-side rendering or static-map workflow. A browser canvas can only read resources the browser is allowed to request, while a server-side service can fetch the page in its rendering environment.


