d3’s built-in transitions make it a great tool to animate arbitrary elements. Here we take advantage of that to animate SVG text elements, taking a sentence and scrambling the letters:
Get started by defining the data setting up the main SVG element:
Line 6 Define the data. The index property stores the actual letter index in the array, while the pos property defines the current letter position. We update this later.
Line 12 A magic number specifying the pixel width of each letter.
Line 16 Assumes you have a #letters element in the DOM.
Next we define an update function that handles data entry and update using the standard d3 pattern:
Line 3 Join the data to the text elements. We specify the join key as the index property; without this the data would be joined on array index, which won’t work here since we shuffle the array contents later.
Lines 5-10 Perform the setup on data entry.
Lines 11-13 On update move the letter to its new position.
With the update function in hand the last step is to create a loop to shuffle the letters, call update, and restore their positions:
Line 3 Call the update function to initially render the letters.
Line 5 Set a timeout to shuffle the letters.
Lines 7-11 Use d3’s built-in shuffle method to shuffle the data. We store the new pos property on the data. Call update.
Lines 13-19 Set a second timeout to restore the letters to their original position.
Line 23 Call loop to get everything going.
That’s all there is to it. Maybe not the most useful application but still fun.
Comments Leave a comment
Leave a comment