Atlaslog
Atlaslog / Examples / OpenLayers / Export Map
OpenLayers · Runnable Example

Export Map

Runnable OpenLayers example: Export Map. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-export-map.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-export-map.html
<!--
  示例:导出图片
  要点:rendercomplete 后合并各图层 canvas,toDataURL 下载 PNG
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>导出图片</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:12px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar button{font:inherit;font-size:12px;padding:5px 11px;border:1px solid #ccd1d9;
       border-radius:4px;background:#fff;color:#16181d;cursor:pointer}
  .bar button:hover{background:#eef0f3}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <button id="export">导出当前视图为 PNG</button>
  <span id="status">提示:导出的图片与当前画布同尺寸</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';

  if (typeof ol === 'undefined') {
    document.getElementById('map').innerHTML =
      '<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var fromLonLat = ol.proj.fromLonLat;

  var marker = new ol.Feature({
    geometry: new ol.geom.Point(fromLonLat([116.391263, 39.907359])),
    name: '天安门'
  });

  marker.setStyle(new ol.style.Style({
    image: new ol.style.Circle({
      radius: 7,
      fill: new ol.style.Fill({ color: '#1f5fd0' }),
      stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 })
    }),
    text: new ol.style.Text({
      text: '天安门',
      offsetY: -16,
      font: '600 13px sans-serif',
      fill: new ol.style.Fill({ color: '#16181d' }),
      stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
    })
  }));

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
      new ol.layer.Vector({ source: new ol.source.Vector({ features: [marker] }) })
    ],
    view: new ol.View({
      center: fromLonLat([116.391263, 39.907359]),
      zoom: 13
    }),
    controls: ol.control.defaults.defaults({ attribution: false })
  });

  var statusEl = document.getElementById('status');

  document.getElementById('export').addEventListener('click', function () {
    statusEl.textContent = '正在等待瓦片加载完成…';

    map.once('rendercomplete', function () {
      try {
        var size = map.getSize();
        var out = document.createElement('canvas');
        out.width = size[0];
        out.height = size[1];
        var ctx = out.getContext('2d');

        /* 每个图层各有一块 canvas,按顺序叠加绘制到同一张画布 */
        var canvases = map.getViewport().querySelectorAll('.ol-layer canvas, canvas.ol-layer');

        Array.prototype.forEach.call(canvases, function (layerCanvas) {
          if (!layerCanvas.width || !layerCanvas.height) return;

          var opacity = layerCanvas.parentNode.style.opacity || layerCanvas.style.opacity;
          ctx.globalAlpha = opacity === '' ? 1 : Number(opacity);

          var transform = layerCanvas.style.transform;
          var matrix;

          if (transform) {
            matrix = transform.match(/^matrix\(([^(]*)\)$/)[1].split(',').map(Number);
          } else {
            matrix = [
              parseFloat(layerCanvas.style.width) / layerCanvas.width,
              0, 0,
              parseFloat(layerCanvas.style.height) / layerCanvas.height,
              0, 0
            ];
          }

          ctx.setTransform.apply(ctx, matrix);
          ctx.drawImage(layerCanvas, 0, 0);
        });

        ctx.globalAlpha = 1;

        var link = document.createElement('a');
        link.href = out.toDataURL('image/png');
        link.download = 'map-export.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        statusEl.textContent = '已导出 ' + size[0] + ' × ' + size[1] + ' 像素';
      } catch (err) {
        statusEl.textContent = '导出失败:' + err.message + '(底图瓦片未开启跨域)';
      }
    });

    map.renderSync();
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLEExport Pdf OpenLayers · EXAMPLEExtent Constrained OpenLayers · EXAMPLEExtent Fit