1.前言
在webGI開發過程中,可能需要進行對點的定位,或者突出某一個點的位置,所以使用postcompose事件實現一個點的光暈動畫讓功能更加直觀。
2.代碼實現
1 //傳入xy坐標 2 function featureLocationByLonLat(x,y) { 3 var geom = new ol.geom.Point([x, y]); 4 //構建feature 5 var feature = new ol.Feature(geom); 6 //定位過去 7 map.getView().fit(geom,{maxZoom:17} ); 8 //閃爍 9 flash(feature); 10 } 11 12 //光暈擴散的周期 13 let duration=1500; 14 function flash(feature) { 15 //開始時間 16 let start = new Date().getTime(); 17 //注冊事件 18 var listenerKey = map.on('postcompose', animate); 19 //事件函數 20 function animate(event) { 21 var vectorContext = event.vectorContext; 22 var frameState = event.frameState; 23 var flashGeom = feature.getGeometry().clone(); 24 var elapsed = frameState.time - start; 25 var elapsedRatio = elapsed / duration; 26 var radius = ol.easing.easeOut(elapsedRatio) * 25 + 5; 27 var opacity = ol.easing.easeOut(1 - elapsedRatio); 28 29 var style = new ol.style.Style({ 30 image: new ol.style.Circle({ 31 radius: radius, 32 stroke: new ol.style.Stroke({ 33 color: 'rgba(255, 0, 0, ' + opacity + ')', 34 width: 1 + opacity, 35 }), 36 }), 37 }) 38 39 vectorContext.setStyle(style); 40 vectorContext.drawGeometry(flashGeom); 41 //重新設置起始時間,開始下一個周期 42 if (elapsed > duration) { 43 start=new Date().getTime(); 44 } 45 // 開始渲染 46 map.render(); 47 } 48 }
效果圖

3.去除動畫
function unFlash(){
//去除事件
map.removeEventListener('postcompose', animate);
}
