本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1082.html ,对应的 官网示例 https://openlayers.org/en/latest/examples/feature-animation.html?q=Geometry
image.pngmap.on('postcompose', function(event) {})
绑定了layer的'postcompose'事件
根据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 //控制是否重复显示地图
})
})
],
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秒中,动画就终止,所以同一时间只有三个动画效果
//实现动画效果的函数
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; //计算出动画已经执行的事件
var elapsedRatio = elapsed / duration;//计算出动画执行进度
//easeOut返回一个0-1之间的数值,渐变式,速度逐渐减慢
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
})
})
});
//通过设置样式来实现图形的变化
vectorContext.setStyle(style);
vectorContext.drawGeometry(flashGeom);
//超过3秒钟就取消绑定
if (elapsed > duration) {
ol.Observable.unByKey(listenerKey); //解绑事件,结束动画效果
return;
}
//可看做动画的“下一帧”
map.render();
}
}
//绑定了addFeature事件,回调函数中调用了flash这个工具函数
source.on('addfeature', function (e) {
flash(e.feature);
});
//每隔1秒添加一个位置随机的要素
window.setInterval(addRandomFeature, 1000);
</script>
</body>
</html>
网友评论