Adobe Animate CC JS动画:实现每次可见时从头播放需求
Solution: Restart Adobe Animate Animation on Scroll into View
The issue with your current code is that it only triggers once when the animation first becomes visible. To fix this, we'll use the Intersection Observer API to detect every time the animation enters (or re-enters) the viewport, and restart it from frame 1 each time.
Step 1: Ensure Your Animation Has a Unique Container ID
First, make sure your exported Adobe Animate animation has a container div with a unique ID. You can set this in Animate's Publish Settings:
- Go to
File > Publish Settings - Under the HTML tab, find the "Container" section and set an ID (e.g.,
myAnimateAnimation)
Step 2: Replace Your Frame 1 Code with This
Paste this code into the first frame of your Animate timeline. It sets up an observer that watches for the animation to enter the viewport, then restarts it:
// Get reference to your animation's container element const animContainer = document.getElementById("myAnimateAnimation"); // Use your container ID here // Create Intersection Observer to detect visibility changes const viewportObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { // When the animation is visible (10% or more in view) if (entry.isIntersecting) { // Restart the animation from frame 1 this.gotoAndPlay(1); } else { // Optional: Pause animation when out of view to save resources this.stop(); } }); }, { threshold: 0.1 // Trigger when 10% of the element is visible (adjust as needed) }); // Start observing the container if it exists if (animContainer) { viewportObserver.observe(animContainer); }
How This Works
- Intersection Observer: This API continuously checks if the animation container is intersecting with the viewport. Unlike one-time scroll listeners, it's efficient and handles both upward and downward scrolling.
- Restart on Visibility: Every time the animation crosses the 10% visibility threshold (adjustable via
threshold),this.gotoAndPlay(1)resets the timeline to frame 1 and starts playing. - Optional Pause: The
elseblock pauses the animation when it's out of view, which helps reduce unnecessary CPU usage. You can remove this if you want the animation to continue playing in the background.
Notes
- If your animation is a nested movie clip instead of the main timeline, replace
thiswith the reference to your movie clip (e.g.,this.myMovieClip). - The
thresholdvalue can be adjusted: use0to trigger as soon as any part of the element is visible, or1to trigger only when the entire element is in view.
内容的提问来源于stack exchange,提问作者MojoRisin
相关产品推荐
相关产品推荐

