This article will discuss how to use GreenSock to achieve the text animation effect shown below.

To achieve this text animation, we need to separate the text and use absolute positioning to position it, but it takes a bit of work to position the text. Using absolute positioning directly, the text will crowd together:

With absolute positioning, text is removed from the normal flow of the document, which is why this happens. Therefore, we need to specify the position of each text on the X axis to achieve normal text placement. The amount of space between the text also depends on the font you choose. Here we are using monospace. What method can be used to arrange the text in the normal document flow position?

A clever solution is to render the text on the page as normal, and then copy it using absolute positioning to adjust the position of the text to be animated according to the normal position of the text above.

Step 1: Create text location references

Start by creating a reference to the text position, the text of a normal document flow. For example, in the image below, you’ll see two h2 wrapped text elements. The first is normal document flow text. The second line uses absolute positioning.

Step 2: Text positioning

We know that we can read the location of any DOM element using the getBoundingClientRect method. You can use this method to read the left value of each text in the text reference, and then use CSS to assign the read value to the position of the text to be animated below.

Of course, you can also use the offsetLeft Property method to get the location of an element, but remember that this method returns the computed left position of the element relative to the page or parent coordinate specified by the offsetParent property, in CSS pixels.

const placeSpans = () => { // for each span in the guide for (var i = 0; i < guideSpans.length; i++) { let guide = guideSpans[i]; let animated = animatedSpans[i]; // get the guide client rect let rect = guide.getBoundingClientRect(); // set the left property of the animate // span to rect.left animated.style.left = rect.left + 'px'; }}Copy the code

The above code first retrieves the position of the normal document flow text and then assigns the position to the text below to be animated to match the position of the above text.

The code address

Step 3: Animate

Basic work done, the following is to achieve animation, you can also reference this effect to write animation. I also use TweenLite in GreenSock for this simple animation by changing the scale and fade properties of the text.

The code address

Step 4: Final implementation

Finally, we had to hide the reference and put the animated text in the right place, and a cool text animation was achieved.

How to animate individual letters with the correct Kerning How to animate individual letters with the correct Kerning