动画线条
通过在每一帧更新GeoJSON源来制作线条动画;
<!DOCTYPE html>
<html lang="en">
<head>
<title>动画线条</title>
<meta property="og:description" content="通过在每一帧更新GeoJSON源来制作线条动画" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<style>
button {
position: absolute;
top: 0;
margin: 20px;
}
#pause::after {
content: '暂停';
}
#pause.pause::after {
content: '播放';
}
</style>
<div id="map"></div>
<button id="pause"></button>
<script>
const map = new maplibregl.Map({
container: 'map',
style:
'https://demotiles.maplibre.org/styles/osm-bright-gl-style/style.json',
center: [0, 0],
zoom: 0.5
});
// 创建一个带有空LineString的GeoJSON源
const geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [[0, 0]]
}
}
]
};
const speedFactor = 30; // 每经度的帧数
let animation; // 存储和取消动画
let startTime = 0;
let progress = 0; // progress = timestamp - startTime
let resetTime = false; // 是否需要重置时间的指示器
const pauseButton = document.getElementById('pause');
map.on('load', () => {
map.addSource('line', {
'type': 'geojson',
'data': geojson
});
// 添加将在动画中修改的线条
map.addLayer({
'id': 'line-animation',
'type': 'line',
'source': 'line',
'layout': {
'line-cap': 'round',
'line-join': 'round'
},
'paint': {
'line-color': '#ed6498',
'line-width': 5,
'line-opacity': 0.8
}
});
startTime = performance.now();
animateLine();
// 点击按钮暂停或播放
pauseButton.addEventListener('click', () => {
pauseButton.classList.toggle('pause');
if (pauseButton.classList.contains('pause')) {
cancelAnimationFrame(animation);
} else {
resetTime = true;
animateLine();
}
});
// 当标签失去或获得焦点时重置startTime和progress
// requestAnimationFrame默认情况下也会在隐藏标签上暂停
document.addEventListener('visibilitychange', () => {
resetTime = true;
});
// 沿着地图以正弦波的形式在圆圈中动画
function animateLine(timestamp) {
if (resetTime) {
// 恢复之前的进度
startTime = performance.now() - progress;
resetTime = false;
} else {
progress = timestamp - startTime;
}
// 完成一个循环后重新开始
if (progress > speedFactor * 360) {
startTime = timestamp;
geojson.features[0].geometry.coordinates = [];
} else {
const x = progress / speedFactor;
// 用一些数学方法绘制正弦波
const y = Math.sin((x * Math.PI) / 90) * 40;
// 将新坐标附加到LineString
geojson.features[0].geometry.coordinates.push([x, y]);
// 然后更新地图
map.getSource('line').setData(geojson);
}
// 请求动画的下一帧
animation = requestAnimationFrame(animateLine);
}
});
</script>
</body>
</html>