概述
区域掩膜的功能也是比较常见的功能呢,本文分享在mapboxGL中结合canvas如何实现。
效果

实现
1. 创建画布
先创建一个map大小的canvas,设置其大小与样式,并添加到地图画布容器中。
const {width, height} = map.getCanvas()
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.position = 'absolute';
canvas.style.top = '0px';
canvas.style.left = '0px';
canvas.style.zIndex = '1';
ctx = canvas.getContext('2d');
map.getCanvasContainer().appendChild(canvas);
2.注册move事件
注册地图的move事件,在地图变化的时候更新掩膜。
map.on('move', addMapModal)
3.核心实现
- 通过map.project实现地理坐标到屏幕坐标的转换;
- 通过globalCompositeOperation = 'source-out'设置反向裁剪;
function addMapModal() {
  ctx.fillStyle = '#ededed';
  ctx.strokeStyle = '#f00';
  ctx.lineWidth = 3;
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const coords = modalData.map(coord => {
    const {x, y} = map.project(coord)
    return [x, y]
  })
  
  ctx.beginPath();
  coords.forEach((coord, index) => {
    index === 0 ? ctx.moveTo(coord[0], coord[1]) : ctx.lineTo(coord[0], coord[1])
  })
  ctx.closePath();
  ctx.fill();
  
  ctx.globalCompositeOperation = 'source-out';
  ctx.rect(0, 0, canvas.width, canvas.height)
  ctx.fill();
  ctx.globalCompositeOperation = 'source-over';
  ctx.beginPath();
  coords.forEach((coord, index) => {
    index === 0 ? ctx.moveTo(coord[0], coord[1]) : ctx.lineTo(coord[0], coord[1])
  })
  ctx.closePath();
  ctx.stroke()
}



















