openlayers中区域掩膜的实现

概述

在前文完成了mapboxGL中区域掩膜的实现。近日有人问到说在openlayers中如何实现,本文就带大家看看如何在openlayers中实现区域掩膜。

实现效果

map1.gif

实现

1. 实现思路

  1. 在地图容器中添加一个canvas,设置其在map之上;
  2. 监听map的postrender事件,每次事件触发重新绘制掩膜;
  3. 通过map.getPixelFromCoordinate实现地理坐标到屏幕坐标的转换;
  4. 通过globalCompositeOperation = 'source-out’设置反向裁剪;

2. 实现代码

1. 添加canvas

const { offsetWidth, offsetHeight } = map.getViewport()
canvas = document.createElement('canvas');
canvas.width = offsetWidth;
canvas.height = offsetHeight;
canvas.style.position = 'absolute';
canvas.style.top = '0px';
canvas.style.left = '0px';
canvas.style.zIndex = '1';
ctx = canvas.getContext('2d');
map.getViewport().appendChild(canvas);

2. 注册map事件

map.on('postrender', e => {
  addMapModal()
})

3. 事件实现

function addMapModal(params) {
const { fillStyle, strokeStyle, lineWidth } = {
  fillStyle: 'rgba(255,255,255,0.8)',
  strokeStyle: '#f00',
  lineWidth: 3,
  ...params
}
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
ctx.clearRect(0, 0, canvas.width, canvas.height)
const coords = modalData.map(coord => {
  return map.getPixelFromCoordinate(ol.proj.fromLonLat(coord))
})

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、付费专栏及课程。

余额充值