...

/

Using transitions for simple animation

Using transitions for simple animation

Game loops are great when you need fine-grained control. But what if you just want an element to animate a little bit when a user does something? You don’t care about the details; you just want a little flourish.

That’s where transitions come in.

Transitions are a way to animate SVG elements by saying “I want this property to change to this new value and take this long to do it”. And you can use easing functions to make it look better.

I won’t go into details about why easing functions are important, but they make movement look more natural. You can read more about it in Disney’s 12 Basic Principles of Animation.

The two we can achieve with easing functions are:

  1. Squash and Stretch
  2. Slow In Slow Out

Let me show you how it works on a small example. We’re drawing a field of 50 by 50 circles that “flash” when touched. The end result looks like there’s a snake following your cursor.

Rainbow snake

You can play with the code here. Follow along as I explain how it works. Tweak parameters and see what happens :smile:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

App

The App component only needs a render method that returns an SVG. Yes, that means it could’ve been a functional stateless component.

Press + to interact
class App extends Component {
render() {
const width = 600,
N = 50,
pos = d3.scalePoint()
.domain(d3.range(N))
.range([0, width])
.padding(5)
.round(true);
return (
<svg width="600" height="600">
{d3.range(N).map(x =>
d3.range(N).map(y =>
<Dot x={pos(x)} y={pos(y)} key={`${x}-${y}`}
maxPos={width} />
))}
</svg>
)
}
}

We’re rendering a 600px by 600px SVG, with 50 nodes per row and column. ...

Access this course and 1400+ top-rated courses and projects.