mapboxGL中区域掩膜的实现

本文介绍了如何在mapboxGL中结合HTML5canvas技术,通过地图的move事件实时创建和更新区域掩膜,利用坐标转换和全局复合操作实现动态裁剪效果。

概述

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

效果

动画.gif

实现

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()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛老师讲GIS

感谢老板支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值