OpenLayers – How to Export Map from Selected Position

exportopenlayers

I an using the example op OpenLayers map export example.

But I want to change start of mapContext.drawImage(canvas, 0, 0); method.

 Array.prototype.forEach.call(
  document.querySelectorAll('.ol-layer canvas'),
  function (canvas) {
    if (canvas.width > 0) {
      const opacity = canvas.parentNode.style.opacity;
      mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
      const transform = canvas.style.transform;
      // Get the transform parameters from the style's transform matrix
      const matrix = transform
        .match(/^matrix\(([^\(]*)\)$/)[1]
        .split(',')
        .map(Number);

      CanvasRenderingContext2D.prototype.setTransform.apply(
        mapContext,
        matrix
      );
      mapContext.drawImage(canvas, 0, 0);
    }
  }
);

I want to export 700×300 size map image that starts from positon 200,200 that I selected.

mapContext.drawImage(canvas, 200, 200, 700,300, 0, 0, 700, 300);

When I set the custom position, the vector items are going different locations. The size of basemap and vector layers are different. So I can not do this.

How can I solve this problem?

Best Answer

It would be easier to produce the entire map canvas as in the example, then draw the required part of that to a new canvas, and export that

const mapCanvas = document.createElement('canvas');
const size = map.getSize();
mapCanvas.width = size[0];
mapCanvas.height = size[1];
const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
  document.querySelectorAll('.ol-layer canvas'),
  function (canvas) {
    if (canvas.width > 0) {
      const opacity = canvas.parentNode.style.opacity;
      mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
      const transform = canvas.style.transform;
      // Get the transform parameters from the style's transform matrix
      const matrix = transform
        .match(/^matrix\(([^\(]*)\)$/)[1]
        .split(',')
        .map(Number);
      // Apply the transform to the export map context
      CanvasRenderingContext2D.prototype.setTransform.apply(
        mapContext,
        matrix
      );
      mapContext.drawImage(canvas, 0, 0);
    }
  }
);
const newCanvas = document.createElement('canvas');
newCanvas.width = 700;
newCanvas.height = 300;
const newContext = newCanvas.getContext('2d');
newContext.drawImage(mapCanvas, 200, 200, newCanvas.width, newCanvas.height, 0, 0, newCanvas.width, newCanvas.height);
if (navigator.msSaveBlob) {
  // link download attribute does not work on MS browsers
  navigator.msSaveBlob(newCanvas.msToBlob(), 'map.png');
} else {
  const link = document.getElementById('image-download');
  link.href = newCanvas.toDataURL();
  link.click();
}
Related Question