概述
前兩天有個(gè)學(xué)員在群里發(fā)出來一張截圖,效果是一個(gè)區(qū)域掩膜+邊框立體陰影效果,咨詢我怎么實(shí)現(xiàn),我看了下心里大概有了一個(gè)想法,只是前兩天比較忙就沒實(shí)現(xiàn),趁著周末就想著驗(yàn)證實(shí)現(xiàn)一下。鑒于學(xué)員的要求,本文使用的是leaflet框架。
效果

效果
實(shí)現(xiàn)思路
- 掩膜和陰影都使用矢量圖層;
- 掩膜借助
turf.difference實(shí)現(xiàn)數(shù)據(jù)的處理; - 注冊(cè)地圖
zoomend事件,計(jì)算當(dāng)前級(jí)別的分辨率,計(jì)算偏移量對(duì)坐標(biāo)點(diǎn)數(shù)據(jù)進(jìn)行偏移,疊加圖層實(shí)現(xiàn)陰影效果。
實(shí)現(xiàn)
1. 使用技術(shù)
- leaflet
- turf.js
2. 實(shí)現(xiàn)代碼
fetch('./data/beijing-boundry.json').then(res => res.json()).then(res => {
res = res.features[0]
const coordsBoundry = res.geometry.coordinates
let shadowLayer = L.layerGroup().addTo(map);
const mask = turf.difference(turf.bboxPolygon([-180, -90, 180, 90]), res);
L.geoJSON(mask, {
style: {
color: '#098dde',
weight: 3,
opacity: 1,
fillColor: '#ffffff',
fillOpacity: 0.5
}
}).addTo(map);
let addShadowLayer = function () {
shadowLayer.clearLayers()
const zoom = map.getZoom()
const res = 360 / (Math.pow(2, zoom) * 256)
const offset = 2 * res
let coords = [...coordsBoundry[0]].map(([lon, lat]) => {
return [lon - offset * 2, lat - offset]
})
const feature = new Feature([coords])
shadowLayer.addLayer(L.geoJSON(feature, {
style: {
color: '#098dde',
weight: 8,
opacity: 0.5,
fill: false
}
}))
}
addShadowLayer()
map.on('zoomend', () => {
addShadowLayer()
})
})
3. 測(cè)試數(shù)據(jù)
測(cè)試數(shù)據(jù)可從https://wwus.lanzouk.com/iAiwo10x18ze獲取。