要实现底部导航栏中多张图片的连续播放动画,以下是几种高效实现方法:
<div class="nav-icon">
<div class="image-stack">
<img src="image1.png" class="active">
<img src="image2.png">
<img src="image3.png">
</div>
</div>
<style>
.image-stack {
position: relative;
width: 24px;
height: 24px;
}
.image-stack img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 0.3s ease;
}
.image-stack img.active {
opacity: 1;
}
</style>
<script>
const images = document.querySelectorAll('.image-stack img');
let currentIndex = 0;
function cycleImages() {
images[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % images.length;
images[currentIndex].classList.add('active');
}
setInterval(cycleImages, 1000); // 每1秒切换一次
</script>
.nav-icon {
width: 24px;
height: 24px;
background-image: url('sprite-sheet.png');
background-position: 0 0;
animation: play 1s steps(4) infinite;
}
@keyframes play {
100% { background-position: -96px; } /* 4张24px宽的图片 */
}
<!-- 引入Lottie库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>
<div id="nav-icon" style="width: 24px; height: 24px;"></div>
<script>
var animation = lottie.loadAnimation({
container: document.getElementById('nav-icon'),
renderer: 'svg',
loop: true,
autoplay: true,
path: 'animation.json' // 你的Lottie动画文件
});
</script>
<canvas id="nav-icon" width="24" height="24"></canvas>
<script>
const canvas = document.getElementById('nav-icon');
const ctx = canvas.getContext('2d');
const images = ['image1.png', 'image2.png', 'image3.png'];
let currentIndex = 0;
const imgElements = [];
// 预加载所有图片
images.forEach(src => {
const img = new Image();
img.src = src;
imgElements.push(img);
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imgElements[currentIndex], 0, 0, 24, 24);
currentIndex = (currentIndex + 1) % images.length;
}
setInterval(draw, 1000);
</script>
transform
和opacity
属性触发GPU加速选择哪种方案取决于你的具体需求: - 简单切换:CSS方案 - 复杂动画:Lottie方案 - 大量帧动画:Sprite或Canvas方案
需要更具体的实现细节或有其他需求,可以进一步讨论优化方案。