openlayers implements path animation

The effect is as follows
Please add image description

main code

import {
    
    Feature} from 'ol';
import {
    
    LineString, Point} from 'ol/geom';
import {
    
    Icon, Stroke, Fill, Style} from 'ol/style';
import {
    
    getVectorContext} from 'ol/render';


// 路径动画图层
let traceSource = new VectorSource({
    
    });
let moveLayer = new VectorLayer({
    
    
    source: traceSource
});
let lastTime;
let distance;

/**
 * @description 创建路径动画图层
 * @param {*} map 地图对象
 * @param {*} lineFeature 路径线段要素
 */
function createMarkAnimation(map, lineFeature){
    
    
	// 根据路径线段的起点,创建移动元素点
	let personGeo = new Point(lineFeature.getGeometry().getFirstCoordinate());
	const markFeature = new Feature({
    
    
		type: 'moveMark',
		geometry: personGeo
	});
	const markStyle = new Style({
    
    
    	image: new Icon({
    
    
        	anchor: [0.5, 0.9],
        	src: person_run	//---自行设置移动元素点的图片路径
    	})
	});
	markFeature.setStyle(markStyle);
	traceSource.addFeature(markFeature);
	map.addLayer(moveLayer);
	// 开始路径动画
	lastTime = Date.now();
	distance = 0;
	moveLayer.on('postrender', e => {
    
    
		startRunAnimation(map, e, 300, lineFeature, personGeo, markStyle);
	});
}

/**
 * @description 开始路径动画
 * @param {*} map_ol 地图
 * @param {*} e postrender事件参数
 * @param {*} speed 移动速度
 * @param {*} feature 路径线段元素
 * @param {*} geometry 运动元素几何对象
 */
function startRunAnimation(map_ol, e, speed, feature, geometry, style) {
    
    
    const time = e.frameState.time;
    const elapsedTime = time - lastTime;
    distance = (distance + (speed * elapsedTime) / 1e6) % 2;
    if (distance >= 1) distance = 0; //从头重新开始运动
    lastTime = time;
    const currentCoordinate = feature.getGeometry().getCoordinateAt(distance > 1 ? 2 - distance : distance);
    geometry.setCoordinates(currentCoordinate);
    const vectorContext = getVectorContext(e);
    vectorContext.setStyle(style);
    vectorContext.drawGeometry(geometry);
    //告诉OpenLayers继续postrender动画
    map_ol.render();
}

Refer to the official website example: https://openlayers.org/en/latest/examples/feature-move-animation.html

Guess you like

Origin blog.csdn.net/qq_29242649/article/details/121338003