Export Map as PNG with OpenLayers
OpenLayersExport an OpenLayers map to PNG by waiting for the rendercomplete event, calling renderSync(), and reading the canvas with toDataURL().
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 to export an OpenLayers map as a PNG image
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.
With map.once(), the event listener fires only once per export, which prevents 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. Make sure 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 instead of waiting for therendercompleteevent - Forgetting
map.renderSync(), without which the render may not trigger immediately - Not selecting the correct canvas element, since 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