canvas绘制切片并导出图片

2019-10-25 00:24:50 浏览数 (1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/GISShiXiSheng/article/details/102712418

概述

本文讲述在canvas中绘制地图切片,并将切片拼接成一个完整图片的实现。

效果

实现

代码语言:javascript复制
<!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>

0 人点赞