Mapbox GL JS: Export map to PNG or PDF?

后端 未结 2 1901
遇见更好的自我
遇见更好的自我 2021-02-02 11:35

I\'m using Mapbox GL JS version 0.32. Is there a way to export the map to a high-res PNG or PDF?

Obviously, I can just screenshot, but it would be nice if there was a m

2条回答
  •  粉色の甜心
    2021-02-02 12:13

    There are two main questions:

    1. How do I get the map canvas as an image?

    Actually, you are doing the right thing, but just too early. Give that map some time to load and fetch the image data when the load event is triggered:

    map.on('load', () => console.log(map.getCanvas().toDataURL()));
    

    2. How do I get that image in high-res?

    By changing window.devicePixelRatio according to your destination dpi, you can trick your browser into generating high-res output. I found that solution in an implementation created by Matthew Petroff, see his code on https://github.com/mpetroff/print-maps. This is the trick he's using for generating high-res output:

    Object.defineProperty(window, 'devicePixelRatio', {
        get: function() {return dpi / 96}
    });
    

    Source

提交回复
热议问题