canvas draw slice and export images

Outline

This article describes the mapping canvas slice, and the slices spliced ​​to implement a complete picture.

effect

After the entire map mosaic

achieve

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <title>map</title>
</head>
<body>
  <button onclick="downLoad()">导出jpg</button>
  <canvas id="canvas" width="800" height="800"></canvas>
  <script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');
    var baseUrl = "http://www.google.cn/maps/vt?lyrs=t@131,r@240000000&gl=cn&";
    baseUrl += "x={x}&y={y}&z={z}";
    var z = 3;
    var size = 255;
    var max = Math.pow(2, z);
    var a = size * max;
    canvas.setAttribute("width", a);
    canvas.setAttribute("height", a);
    for(var x = 0; x< max; x++) {
      for(var y = 0; y< max; y++) {
        var img = loadImageAsync(x, y, z);
        img.then(_img => {
          var _x = Number(_img.getAttribute("x"));
          var _y = Number(_img.getAttribute("y"));
          ctx.drawImage(_img, _x * size, _y * size);
        });
      }
    }

    function downLoad(){
      var strDataURI = canvas.toDataURL("image/jpeg");
      var a = document.createElement("a");
      a.href = strDataURI;
      a.download = name;
      a.click();
    }
    function loadImageAsync(x, y, z) {
      return new Promise((resolve, reject)=>{
        var image = new Image();
        image.crossOrigin = "Anonymous";
        var src = baseUrl;
        src = src.replace(/{x}/g, x);
        src = src.replace(/{y}/g, y);
        src = src.replace(/{z}/g, z);
        image.src = src;
        image.setAttribute("x", x);
        image.setAttribute("y", y);
        image.setAttribute("z", z);
        image.onload = function () {
          resolve(image);
        }
        image.onerror = function () {
          reject(new Error('Could not load image at '+url))
        }
      })
    }
  </script>
</body>
</html>
Published 284 original articles · won praise 398 · Views 1.1 million +

Guess you like

Origin blog.csdn.net/GISShiXiSheng/article/details/102712418