Export Map as PNG with MapLibre GL JS
MapLibre GL JSCapture the current MapLibre GL JS map view as a downloadable PNG image using the WebGL canvas export API.
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 it works
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.
Note that 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: exports produce a blank image - Expecting DOM markers to appear in the export: only WebGL-rendered content is captured; DOM overlays are not on the canvas
- Not waiting for tiles to load: export immediately 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