Creating a Smooth Train Animation with Interpolation in Frontend Development
This article explains how to create a smooth train animation on a web page by sampling track points, using linear interpolation for position and angle, and dynamically adjusting speed, with JavaScript code examples illustrating the implementation.
The article describes the implementation of a train animation used in the Taobao Play Platform, detailing how the visual effect is achieved through simple interpolation techniques.
Data Collection : Track points are sampled along the rail, with denser points in high‑curvature sections and sparser points on smooth segments. The collected points form the basis for subsequent calculations.
Determining Position : Assuming constant speed, each frame updates the traveled distance L using the time interval inter and speed speed . With the current distance and the sampled points, the train’s segment and interpolation factor q are found, then the position is computed by linear interpolation: train.x = (1 - q) * p[i].x + q * p[i+1].x train.y = (1 - q) * p[i].y + q * p[i+1].y
Determining Angle : To align the train with the rail direction, the angle between two adjacent points (e.g., A and B) is calculated. Because sampled points may be sparse, the angle itself is interpolated using the same factor q : train.theta = (1 - q) * p[i].theta + q * p[i+1].theta
Speed Variation : Instead of a constant speed, the train’s speed can be varied based on a simple energy‑conservation model, where speed squared is linearly related to the train’s height: train.speed = Math.sqrt(C1 - C2 * train.y)
Code Example (simplified for clarity): train.speed = 10; train.L = 0; setInterval(function(){ var inter = 50; train.L += inter * train.speed; // compute train.x, train.y, train.theta based on L and sampled points // render train at (train.x, train.y) with rotation train.theta }, 50);
Conclusion : The core of the animation is interpolation, which ensures continuous and smooth updates of both position and rotation each frame. While fitting Bézier curves could produce a more perfect path, the sampled points combined with linear interpolation are sufficient for a practical and performant animation.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.