本文基于騰訊課堂老胡的課《跟我學(xué)Openlayers--基礎(chǔ)實例詳解》做的學(xué)習(xí)筆記筷登,使用的openlayers 5.3.x api爹脾。
源碼 見 1082.html 更啄,對應(yīng)的 官網(wǎng)示例 https://openlayers.org/en/latest/examples/feature-animation.html?q=Geometry
map.on('postcompose', function(event) {})
綁定了layer的'postcompose'事件
根據(jù)framestate的時間計算波紋半徑
<!DOCTYPE html>
<html>
<head>
<title>水紋效果</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css" />
<script src="../include/ol.js"></script>
</head>
<style></style>
<body>
<div id="map" class="map"></div>
<script>
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
wrapX: false //控制是否重復(fù)顯示地圖
})
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 1
})
});
var source = new ol.source.Vector({
wrapX: false
});
var vector = new ol.layer.Vector({
source: source
});
map.addLayer(vector);
//添加一個位置隨機的要素
function addRandomFeature() {
var x = Math.random() * 360 - 180;
var y = Math.random() * 180 - 90;
var geom = new ol.geom.Point(ol.proj.fromLonLat([x, y]));
var feature = new ol.Feature(geom);
source.addFeature(feature);
}
var duration = 3000; //超過3秒中纳令,動畫就終止柠贤,所以同一時間只有三個動畫效果
//實現(xiàn)動畫效果的函數(shù)
function flash(feature) {
var start = new Date().getTime();
var listenerKey = map.on('postcompose', animate);
//綁定后渲染事件帮孔,可看做動畫的“start”
function animate(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
var flashGeom = feature.getGeometry().clone();//克隆方法雷滋,獲取當前動畫的點位坐標集合
var elapsed = frameState.time - start; //計算出動畫已經(jīng)執(zhí)行的事件
var elapsedRatio = elapsed / duration;//計算出動畫執(zhí)行進度
//easeOut返回一個0-1之間的數(shù)值不撑,漸變式,速度逐漸減慢
var radius = ol.easing.easeOut(elapsedRatio) * 25 + 5;//計算半徑
var opacity = ol.easing.easeOut(1 - elapsedRatio);//計算透明度
console.log(elapsedRatio);
console.log("easeOut:"+ol.easing.easeOut(elapsedRatio));
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
stroke: new ol.style.Stroke({
color: 'rgba(255, 0, 0, ' + opacity + ')',
width: 0.25 + opacity
})
})
});
//通過設(shè)置樣式來實現(xiàn)圖形的變化
vectorContext.setStyle(style);
vectorContext.drawGeometry(flashGeom);
//超過3秒鐘就取消綁定
if (elapsed > duration) {
ol.Observable.unByKey(listenerKey); //解綁事件晤斩,結(jié)束動畫效果
return;
}
//可看做動畫的“下一幀”
map.render();
}
}
//綁定了addFeature事件焕檬,回調(diào)函數(shù)中調(diào)用了flash這個工具函數(shù)
source.on('addfeature', function (e) {
flash(e.feature);
});
//每隔1秒添加一個位置隨機的要素
window.setInterval(addRandomFeature, 1000);
</script>
</body>
</html>