Export Map as PNG with OpenLayers
OpenLayersCapture the current OpenLayers map view as a downloadable PNG image using the canvas export API.
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '© <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) })
],
view: new ol.View({ center: ol.proj.fromLonLat([2.3522, 48.8566]), zoom: 13 })
});
function exportMap() {
map.once('rendercomplete', function() {
var canvas = document.querySelector('#map canvas');
if (canvas) {
var link = document.createElement('a');
link.download = 'map-export.png';
link.href = canvas.toDataURL('image/png');
link.click();
}
});
map.renderSync();
}How it works
OpenLayers renders the map on an HTML Canvas element. The rendercomplete event fires once all tiles and layers have been drawn, making it safe to capture the canvas content.
map.renderSync() forces an immediate render. After rendering completes, canvas.toDataURL() converts the canvas pixels to a PNG data URL. A temporary link element triggers the browser download dialog.
The map.once() method ensures the event listener fires only once per export, preventing duplicate downloads.
Key APIs
| API | Description | Docs |
|---|---|---|
rendercomplete event |
Fires when all layers finish rendering | openlayers.org |
map.renderSync() |
Force synchronous render | openlayers.org |
canvas.toDataURL() |
Convert canvas to image data URL | MDN |
FAQ
Why does the export sometimes produce a blank image?
Tiles from external servers may have CORS restrictions. The canvas becomes “tainted” and toDataURL() fails silently. Ensure the tile source supports CORS headers.
Can I export at a higher resolution?
Yes. Set a pixelRatio on the map or use ol.Map’s getSize() and render to an off-screen canvas at a larger size.
Common mistakes
- Calling
toDataURL()before tiles finish loading: always wait for therendercompleteevent - Forgetting
map.renderSync(): without it, the render may not trigger immediately - Not selecting the correct canvas element: OpenLayers may create multiple canvas elements within the map container
Build maps using OpenLayers with AI
Generate code like this export map as png with openlayers example using the OpenLayers skill in your IDE.
Related Examples
- Initialize an OpenLayers Map
- See how to do this in Leaflet, MapLibre GL JS or MapTiler SDK