前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mapboxGL中区域掩膜的实现

mapboxGL中区域掩膜的实现

作者头像
lzugis
发布2024-01-11 10:33:03
1560
发布2024-01-11 10:33:03
举报

概述

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

效果

动画.gif
动画.gif

实现

1. 创建画布

先创建一个map大小的canvas,设置其大小与样式,并添加到地图画布容器中。

代码语言:javascript
复制
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事件,在地图变化的时候更新掩膜。

代码语言:javascript
复制
map.on('move', addMapModal)

3.核心实现

  • 通过map.project实现地理坐标到屏幕坐标的转换;
  • 通过globalCompositeOperation = 'source-out'设置反向裁剪;
代码语言:javascript
复制
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()
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 效果
  • 实现
    • 1. 创建画布
      • 2.注册move事件
        • 3.核心实现
        相关产品与服务
        容器服务
        腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档