2
votes

I am trying to export openlayers 3 map to PNG.

This example is working well http://openlayers.org/en/master/examples/export-map.html , but the export image width and height are double than the original map canvas.

If the map canvas is 1330x440, I get the exported png image as 2660x880 pixels.

Any idea how to get the export size same as canvas size ?

1
Are you using a Mac with Retina display? - kryger
Is there anything missing to your question? - Jonatas Walker

1 Answers

7
votes

This is because your device pixel ratio is 2, because you have a HiDPI (Retina) display.

You can either configure your map with {pixelRatio: 1} and get a blurry map, or scale the exported image when ol.has.DEVICE_PIXEL_RATIO is not equal 1:

map.once('postcompose', function(event) {
  var dataURL;
  var canvas = event.context.canvas;
  if (ol.has.DEVICE_PIXEL_RATIO == 1) {
    dataURL = canvas.toDataURL('image/png');
  } else {
    var targetCanvas = document.createElement('canvas');
    var size = map.getSize();
    targetCanvas.width = size[0];
    targetCanvas.height = size[1];
    targetCanvas.getContext('2d').drawImage(canvas,
        0, 0, canvas.width, canvas.height,
        0, 0, targetCanvas.width, targetCanvas.height);
    dataURL = targetCanvas.toDataURL('image/png');
  }
});
map.renderSync();