Leaflet实现框选截图 网页框选截图

我们要实现一些类似以网页截图的功能,比如下面
image.png
我们需要借助

项目预览地址

html
  
  
  
  
  

  
  
  
  

  
css
#map {
  height: 100vh;
  width: 100vw;
}
js
  • 第一步:加载地图
var map = L.map("map").setView([60, 30], 8);
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
  attribution:
    '© OpenStreetMap contributors'
}).addTo(map);

image.png

  • 第二步:加载工具栏
let points = [];//保存点位

var featureGroup = L.featureGroup().addTo(map);
//只保留矩形截图
var drawControl = new L.Control.Draw({
  draw: {
    polygon: false,
    polyline: false,
    circle: false,
    marker: false
  },
  edit: {
    featureGroup: featureGroup,
    edit: false,
    remove:false
  }
}).addTo(map);
map.on("draw:created", function (e) {
  featureGroup.addLayer(e.layer);
  let latlngs = e.layer._latlngs;
  points = latlngs;
  var r = confirm("是否截图当前框选");
  if (r == true) {
    createMapImage();//下面的截图方法
  } else {
    console.log("您按了取消!");
  }
  featureGroup.removeLayer(e.layer);
});

image.png

  • 第三步:添加截图代码
function createMapImage() {
  let bounds = this.map.getBounds(),
    zero = [bounds._northEast.lat, bounds._southWest.lng],
    // 计算当前 视窗内的 原点经纬度 ==> 对应的屏幕坐标 (地图位移及缩放时计算 startPoint的偏移量)必须!!!
    zeroPoint = map.latLngToLayerPoint(zero);
  let startPoint = map.latLngToLayerPoint(points[1]), // latlng 转 屏幕坐标 计算 起点及宽高
    endPoint = map.latLngToLayerPoint(points[points.length - 1]),
    width = Math.abs(startPoint.x - endPoint.x),
    height = Math.abs(startPoint.y - endPoint.y);
  html2canvas(document.getElementById("map"), {
    useCORS: true,
    onrendered: function (canvas) {
      // canvas is the final rendered  element
      downloadIamge(
        canvas,
        startPoint.x - zeroPoint.x,
        startPoint.y - zeroPoint.y,
        width,
        height
      );
    }
  });
}

function downloadIamge(
  canvas,
  capture_x,
  capture_y,
  capture_width,
  capture_height
) {
  // 创建一个用于截取的canvas
  var clipCanvas = document.createElement("canvas");
  clipCanvas.width = capture_width;
  clipCanvas.height = capture_height;
  // 截取图片
  clipCanvas
    .getContext("2d")
    .drawImage(
      canvas,
      capture_x,
      capture_y,
      capture_width,
      capture_height,
      0,
      0,
      capture_width,
      capture_height
    );
  var clipImgBase64 = clipCanvas.toDataURL(); // 生成图片url
  // 下载图片
  let link = document.createElement("a");
  link.href = clipImgBase64; //下载链接
  link.setAttribute("download", new Date().toLocaleString() + "_截图.png");
  link.style.display = "none"; //a标签隐藏
  document.body.appendChild(link);
  link.click(); // 点击下载
  document.body.removeChild(link); // 移除a标签
}

项目预览地址
源码地址

你可能感兴趣的:(Leaflet实现框选截图 网页框选截图)