Export Map as PNG with MapLibre GL JS
MapLibre GL JSExport a MapLibre GL JS map as a PNG by enabling preserveDrawingBuffer and passing map.getCanvas().toDataURL() to a download link.
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
center: [14.42, 50.08],
zoom: 13,
preserveDrawingBuffer: true
});
map.addControl(new maplibregl.NavigationControl());
document.getElementById('export-btn').addEventListener('click', () => {
const canvas = map.getCanvas();
const link = document.createElement('a');
link.download = 'map-export.png';
link.href = canvas.toDataURL('image/png');
link.click();
}); How to export a MapLibre GL JS map as a PNG image
MapLibre renders the map on a WebGL canvas. Setting preserveDrawingBuffer: true in the constructor keeps the canvas content available for export. Without this flag, toDataURL() returns a blank image.
Clicking the export button calls canvas.toDataURL('image/png') to generate a data URL, then creates a temporary download link. The browser downloads the current map view as a PNG file.
Enabling preserveDrawingBuffer has a slight performance cost because the GPU cannot discard the back buffer between frames. Only enable it when export functionality is needed.
Key APIs
| API | Description | Docs |
|---|---|---|
preserveDrawingBuffer |
Keep canvas content for export | maplibre.org docs |
map.getCanvas() |
Get the WebGL canvas element | maplibre.org docs |
canvas.toDataURL() |
Export canvas to image data URL | MDN docs |
FAQ
Why is my exported image blank?
You likely forgot preserveDrawingBuffer: true in the Map constructor. WebGL clears the drawing buffer after each frame by default.
Can I export at a higher resolution?
Not directly with toDataURL(). For higher resolution, use the MapTiler Static Maps API or resize the map container temporarily before exporting.
Common mistakes
- Forgetting
preserveDrawingBuffer: true, which makes exports blank - Expecting DOM markers to appear in the export. Only WebGL-rendered content is captured, and DOM overlays are not on the canvas
- Not waiting for tiles to load. Exporting right after initialization may capture a partially rendered map
Build maps using MapLibre GL JS with AI
Generate code like this export map as png with maplibre gl js example using the MapLibre GL JS skill in your IDE.
Related examples
- Initialize a MapLibre GL JS Map
- See how to do this in Leaflet, MapTiler SDK, or OpenLayers