如何在Anime.js或JavaScript中实现滚动触发的Seek动画?
Hey there! I’ve implemented this exact kind of scroll-controlled animation before, and it’s actually pretty straightforward once you map scroll progress to the animation’s timeline. Let’s break it down step by step:
1. Setup Your Base
First, make sure you’ve got anime.js included in your project. Then set up a simple DOM element to animate—here’s a quick example:
<div class="animated-box"></div>
Add some basic CSS to style it:
.animated-box { width: 120px; height: 120px; background: #2196F3; position: fixed; top: 50%; left: 20px; transform: translateY(-50%); border-radius: 8px; }
2. Create Your Animation Instance
Define the animation you want to control, but don’t autoplay it—we’ll handle playback via scroll:
const boxAnim = anime({ targets: '.animated-box', translateX: window.innerWidth - 140, // Move from left to right edge scale: 1.8, // Slight zoom rotate: 360, // Full spin duration: 6000, // Total animation length (6 seconds) easing: 'easeInOutCubic', autoplay: false // Critical: disable auto-start });
3. Connect Scroll to Animation Seek
This is the core part—listen to the scroll event, calculate how far the user has scrolled, and use that to jump the animation to the right time point:
function updateAnimationOnScroll() { // Calculate total scrollable area const totalScrollable = document.documentElement.scrollHeight - window.innerHeight; // Get scroll progress as a 0-1 value (clamped to avoid out-of-bounds) const scrollPercent = Math.max(0, Math.min(1, window.scrollY / totalScrollable)); // Convert percentage to animation time (milliseconds) const targetTime = scrollPercent * boxAnim.duration; // Jump the animation to the calculated time boxAnim.seek(targetTime); } // Attach the scroll listener window.addEventListener('scroll', updateAnimationOnScroll); // Run once on load to set initial animation position updateAnimationOnScroll();
4. Optimize for Performance
Scroll events fire extremely frequently, so add a debounce to reduce unnecessary function calls and keep things smooth:
function debounce(func, delay = 15) { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } // Replace the raw listener with the debounced version window.addEventListener('scroll', debounce(updateAnimationOnScroll));
How It Works
This uses the same core logic as the progress bar-controlled seek example you’re referencing—we just swap the progress bar’s input value with the page’s scroll progress. The seek() method lets us jump directly to any point in the animation’s timeline, so mapping the scroll percentage to the animation’s total duration creates that seamless "scroll to control animation" effect.
内容的提问来源于stack exchange,提问作者Anas Ahmed

