1、 导入FileSaver.js

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

2、设置数据源跨域

crossOrigin: “Anonymous”

  1. const key = '8a5c2b00e94b49659861e064c37f778d'
  2. /* 天地图矢量图层 */
  3. const TianDiMap_vec = new ol.layer.Tile({
  4. title: "天地图矢量图层",
  5. source: new ol.source.XYZ({
  6. url: 'http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=' +
  7. key,
  8. wrapX: false,
  9. crossOrigin: "Anonymous"
  10. })
  11. })
  12. /* 天地图注记图层 */
  13. const TianDiMap_cva = new ol.layer.Tile({
  14. title: "天地图矢量注记图层",
  15. source: new ol.source.XYZ({
  16. url: 'http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' +
  17. key,
  18. wrapX: false,
  19. crossOrigin: "Anonymous"
  20. })
  21. })

3、下载

  1. <body>
  2. <button onclick="exportImg()">导出图片</button>
  3. <div id="map_container">
  4. </div>
  5. <script>
  6. var map = new ol.Map({
  7. target: "map_container",
  8. layers: [TianDiMap_vec, TianDiMap_cva],
  9. view: new ol.View({
  10. center: [114, 30],
  11. projection: 'EPSG:4326',
  12. zoom: 4
  13. })
  14. })
  15. function exportImg() {
  16. map.once('postcompose', function (event) {
  17. const canvas = event.context.canvas
  18. console.log(canvas)
  19. canvas.toBlob(function (blob) {
  20. console.log(blob)
  21. saveAs(blob, 'map.png')
  22. })
  23. })
  24. map.renderSync()
  25. }
  26. </script>
  27. </body>

4、如果是图层中有地图文档,也需设置跨域

  1. var docLayer = new Zondy.Map.Doc("",docName , {
  2. ip: "localhost",
  3. port: 6163,
  4. crossOrigin: "Anonymous"
  5. });