Animating Words with d3

Updated Feb 14, 2018

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:

Getting started Copy
import {
  select  as d3_select,
  shuffle as d3_shuffle
from 'd3';
let data = 'Does this make any sense?'.split('').map( (d, i) => ({
  letter  : d,
  index   : i,
  pos     : i
const LETTER_WIDTH = 22;
const WIDTH        = LETTER_WIDTH * data.length;
const HEIGHT       = 80;
const svg = d3_select('#letters').append('svg')
  .attr('width', WIDTH)
  .attr('height', HEIGHT)
    .attr('transform''translate(0,' + (HEIGHT/2+ ')');

Next we define an update function that handles data entry and update using the standard d3 pattern:

Update Copy
function update (data) {
  const text = svg.selectAll('text').data(data, d => d.index);
    .attr('fill', d => d.letter === '?' ? 'tomato' : '#000')
    .attr('x', (d, i) => LETTER_WIDTH*d.pos)
    .text(d => d.letter)
      .attr('x', (d, i) => LETTER_WIDTH*d.pos);

With the update function in hand the last step is to create a loop to shuffle the letters, call update, and restore their positions:

The loop Copy
function loop () {
  window.setTimeout(function () {
    data = d3_shuffle(data).map( (d, i) => {
      d.pos = i;
      return d;
    window.setTimeout(function () {
      data = (d, i) => {
        d.pos = d.index;
        return d;
    }, 2000);
  }, 2000);

That’s all there is to it. Maybe not the most useful application but still fun.

Comments Leave a comment

  • JamesBak
    Great looking website. Think you did a bunch of your very own html coding.
    • EssyCodeModerator
      Thanks for saying so. I wrote a custom WordPress theme and decided to re-invent the wheel and also do the code example generation and styling from scratch.

Leave a comment