How to Convert a Leaflet Map to an Image
Export a Leaflet map as PNG with leaflet-image, handle CORS and HTML layers, preserve attribution, and automate captures with ScreenshotNeo.

Use leaflet-image for a client-side PNG export when your tiles and overlays support CORS. It reads supported Leaflet layers into a canvas, which you can display or save with canvas.toDataURL(). Canvas-rendered vectors can be included; arbitrary HTML such as L.divIcon content, controls, and legends cannot.
If you need the complete browser view, including HTML overlays, use a DOM capture method such as html2canvas or a browser screenshot. For server-side captures without browser setup, ScreenshotNeo can render the page through one API request.
Choose the export method
| Method | Use it when | Limitations |
|---|---|---|
leaflet-image |
Your map uses image tiles and Canvas-compatible vectors | Requires CORS-enabled images; excludes arbitrary HTML |
| DOM capture with html2canvas | You need a map container plus surrounding HTML | Cross-origin images may be skipped or taint the canvas; output is reconstructed from the DOM |
| Leaflet print/export plugin | You need print-oriented sizing or higher-resolution output | Features differ by plugin; verify current compatibility |
| Hosted screenshot service | You need repeatable server-side exports, automation, or many URLs | Requires provider credentials, API rules, and a cost review |
Export a Leaflet map with leaflet-image
1. Load Leaflet, a map, and the plugin
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-image@0.4.0/leaflet-image.js"></script>
<div id="map" style="width: 900px; height: 600px"></div>
<button id="export" type="button">Download PNG</button>
<script>
const map = L.map('map', { preferCanvas: true }).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);
L.circle([51.505, -0.09], {
radius: 500,
color: '#2563eb',
fillColor: '#60a5fa',
fillOpacity: 0.35,
renderer: L.canvas()
}).addTo(map);
L.marker([51.51, -0.1]).addTo(map);
document.getElementById('export').addEventListener('click', () => {
leafletImage(map, (error, canvas) => {
if (error) {
console.error('Map export failed:', error);
return;
}
const link = document.createElement('a');
link.download = 'leaflet-map.png';
link.href = canvas.toDataURL('image/png');
link.click();
});
});
</script>
The plugin callback receives an error or a canvas. Always handle the error before calling toDataURL(). The output canvas follows the map’s rendered size, so set the map container dimensions before exporting.

2. Wait until tiles and overlays finish loading
Starting an export while tiles are still loading can produce a partial image. Track tile loading and delay export until the map has settled:
const tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
crossOrigin: true,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
function waitForTiles(layer) {
return new Promise((resolve, reject) => {
let settled = false;
const finish = () => {
if (!settled) {
settled = true;
resolve();
}
};
layer.once('load', finish);
layer.on('tileerror', reject);
setTimeout(finish, 15000);
});
}
document.getElementById('export').onclick = async () => {
try {
await waitForTiles(tileLayer);
leafletImage(map, (error, canvas) => {
if (error) return console.error(error);
document.body.appendChild(canvas);
// Or: canvas.toBlob(blob => saveBlob(blob, 'map.png'), 'image/png');
});
} catch (error) {
console.error('A tile failed to load:', error);
}
};
In production, also listen for tile errors in the browser console. A timeout fallback prevents a permanently missing tile from blocking the export, but the resulting image may be incomplete.
3. Use Canvas for vectors that must appear
With Leaflet 1.x, configure paths with a Canvas renderer or set preferCanvas: true on the map. SVG paths may not be included by the export plugin in the way you expect.
const canvasRenderer = L.canvas({ padding: 0.5 });
L.polyline([[51.49, -0.1], [51.52, -0.08]], {
renderer: canvasRenderer,
color: '#dc2626',
weight: 5
}).addTo(map);
const polygon = L.polygon([
[51.50, -0.12], [51.52, -0.1], [51.51, -0.06]
], { renderer: canvasRenderer }).addTo(map);
Control output size and format
The exported canvas uses the map viewport dimensions. Resize the map container before capture, call map.invalidateSize(), and then export:
const mapElement = document.getElementById('map');
mapElement.style.width = '1800px';
mapElement.style.height = '1200px';
map.invalidateSize();
requestAnimationFrame(() => {
leafletImage(map, (error, canvas) => {
if (error) throw error;
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'), {
href: url,
download: 'map@2x.png'
});
a.click();
URL.revokeObjectURL(url);
}, 'image/png');
});
});
PNG preserves sharp labels and transparency. JPEG creates smaller files but loses transparency and introduces compression artifacts. WebP can be smaller where your consumers support it. The browser’s canvas API determines which encodings are available.
CORS: the requirement that decides whether export works
Remote tile images must be readable by the browser. Leaflet’s crossOrigin option sets the image attribute, but it cannot grant permission that the tile server does not return. The server must send an appropriate Access-Control-Allow-Origin response header. See the Leaflet TileLayer reference.
const tiles = L.tileLayer('https://tiles.example.com/{z}/{x}/{y}.png', {
crossOrigin: 'anonymous'
}).addTo(map);
Open the browser’s network panel and inspect a tile response. If the response lacks the required CORS header, client-side code cannot make that image safe to read. Use a provider that supports CORS, proxy the tiles from a server you control while respecting provider terms, or use a server-side capture workflow.
Exporting markers, labels, and HTML overlays
Canvas-compatible content
- Image tiles with valid CORS headers
- Canvas-rendered polylines, polygons, circles, and other paths
- Images whose servers permit cross-origin access
Content leaflet-image does not rasterize
L.divIconHTML markers- Zoom controls, attribution controls, legends, and arbitrary DOM nodes
- HTML labels positioned above the map
The leaflet-image project explains that it does not rasterize HTML. To include these elements, either redraw them as export-compatible layers or capture the map container as rendered HTML.
Capture the map DOM with html2canvas
html2canvas reconstructs an image from DOM information. It is useful when controls, legends, and HTML markers matter, but its result may differ from the browser’s actual pixels.
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
async function exportMapElement() {
const element = document.getElementById('map');
const canvas = await html2canvas(element, {
useCORS: true,
backgroundColor: '#ffffff',
scale: window.devicePixelRatio
});
const link = document.createElement('a');
link.download = 'leaflet-dom-map.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
</script>
useCORS: true still depends on each image server’s CORS headers. Cross-origin images without permission can be omitted or taint the canvas.
Preserve attribution and provider terms
Keep the attribution required by your tile and data providers. For OpenStreetMap-based material, Leaflet’s quick start points production users to the OSM tile usage policy. If attribution is rendered as a control that your export method omits, add it to the saved image or publish it alongside the image so it remains with the map.
Or skip the browser setup
ScreenshotNeo renders a URL through one request and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://example.com/map \
-o map.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://example.com/map"},
timeout=90,
)
r.raise_for_status()
open("map.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com/map'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('map.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its 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.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Blank or missing basemap | Tile host does not allow cross-origin reads, or tiles have not loaded | Set crossOrigin, verify response headers, wait for the tile load event, and inspect tile errors |
| “Tainted canvas” security error | An image was loaded without usable CORS permission | Use a CORS-enabled source, a compliant proxy, or server-side capture |
| Custom marker or legend missing | It is HTML, such as L.divIcon or a control |
Use html2canvas/browser capture or redraw it on a Canvas layer |
| Vector shapes missing | Layer uses an unsupported renderer | Set preferCanvas: true or pass renderer: L.canvas() |
| Only part of the map appears | Export ran before all tiles finished | Wait for loading, then export; handle timeout and tile error paths |
| Image differs from what users see | DOM capture reconstructs pixels rather than taking a native screenshot | Use leaflet-image for supported layers or a real browser screenshot service |
| Attribution is absent | The attribution control was not included in the raster output | Draw attribution into the export or provide it next to the image |
Performance, reliability, and cost notes
- Pixels drive memory: doubling width and height creates roughly four times as many canvas pixels. Capture at the smallest useful dimensions.
- Wait deliberately: network idle or an explicit tile-loaded condition is more reliable than a short fixed delay.
- Cache repeated exports: identical map views can be reused rather than rendered again. In ScreenshotNeo, choose a cache TTL that fits how often the map changes.
- Prefer deterministic inputs: set the viewport, zoom, center, device scale, timezone, and any required headers or cookies explicitly.
- Handle failures: treat tile errors, bot checks, blank pages, and timeouts as distinct outcomes. ScreenshotNeo exposes page verdict and billing headers so callers can record what happened.
- Mind provider terms: tile access, attribution, rate limits, and redistribution rights remain your responsibility after export.
FAQ
Can Leaflet export directly without a plugin?
Leaflet renders the map but does not provide a universal file-export API. Use a layer-aware plugin, DOM capture, a print plugin, or a server-side browser.
Why does my map work on screen but fail to export?
Browsers can display cross-origin images without allowing scripts to read their pixels. Export requires the tile server’s CORS response as well as the correct client setting.
Can I include a Leaflet popup?
A popup’s HTML is outside leaflet-image’s rasterization support. Capture the DOM or recreate the popup as Canvas content before exporting.
How do I create a PDF?
Use a print/export plugin or a browser/PDF capture workflow. ScreenshotNeo’s capture_pdf MCP tool and PDF options support server-side page output.
What image format should I choose?
Choose PNG for lossless labels and transparency, JPEG for broad compatibility and smaller photographic files, and WebP when your consumers support it and file size matters.


