如何使用OpenLayers制作截图工具?

时间:2019-07-09 12:07:29

标签: openlayers

我是OpenLayers的新手,想知道如何制作类似Windows的Snipping Tool。

我有一张地图,并且需要能够在地图上绘制矩形,进行屏幕截图并将其加载到其他区域的工具。

那将使用JavaScript完成。

我试图在互联网上找到类似的东西,但是没有运气。

1 个答案:

答案 0 :(得分:0)

这是这些示例https://openlayers.org/en/latest/examples/box-selection.html https://openlayers.org/en/latest/examples/export-map.html的组合,其中裁剪后的画布被导出为PNG,但是您可以随心所欲地做。

  var vectorSource = new ol.source.Vector({
    url: 'https://openlayers.org/en/v5.3.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  });


  var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: vectorSource
      })
    ],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  // a normal select interaction to handle click
  var select = new ol.interaction.Select();
  map.addInteraction(select);

  var selectedFeatures = select.getFeatures();

  // a DragBox interaction used to select features by drawing boxes
  var dragBox = new ol.interaction.DragBox({
    condition: ol.events.condition.platformModifierKeyOnly
  });

  map.addInteraction(dragBox);

  dragBox.on('boxend', function() {

    // convert geometry to pixels (extent doesn't gives correct bounds when view is rotated)

    var left = Infinity;
    var top = Infinity;
    var bottom = -Infinity;
    var right = -Infinity;

    dragBox.getGeometry().getCoordinates()[0].forEach(function(coord) {
      var pixel = map.getPixelFromCoordinate(coord);
      left = Math.min(left, pixel[0]);
      right = Math.max(right, pixel[0]);
      top = Math.min(top, pixel[1]);
      bottom = Math.max(bottom, pixel[1]);
    });

    map.once('rendercomplete', function(event) {
      var image = event.context.canvas;
      var canvas = document.createElement('canvas');
      canvas.width = right - left;
      canvas.height = bottom - top;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(image, left, top, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);

      if (navigator.msSaveBlob) {
        navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
      } else {
        canvas.toBlob(function(blob) {
          saveAs(blob, 'map.png');
        });
      }
    });
    map.renderSync();
  });
html, body, .map {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

.ol-dragbox {
    background-color: rgba(255,255,255,0.4);
    border-color: rgba(100,150,0,1);
}
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<div id="map" class="map"></div>