Signals & Envelopes

Using time with requestAnimationFrame ()

The cleanest way to create animations in the browser is by calling requestAnimationFrame (), which will call the function passed into it (called a callback function) when the browser deems itself ready for the next frame.

The problem with this is that the framerate will be completely dependant on the browser, and operating system, and device specifications. Even if you know these things, you may find that the framerate varies over time, depending on the availability of those resources the device needs to spend on preparing the next animation frame.

This means that animations that depend solely on iterating a frameCount variable may run faster in some contexts, and slower in others.

In order to ameliorate this problem, requestAnimationFrame passes the elapsed time in milliseconds to the callback function, when it calls it for the next frame.

Phase Ramps

For repetative (or periodic) motion, often the simplest way to imagine how things change is to think in terms of phase, which refers to how far along the present moment is between the start ( = 0) and the finish ( = 1).

For example:

Tricks with Phase Ramps

Using phase directly, like the above example, creates linear motion. The nice thing about dealing with values between 0 - 1, is that we can modulate the curve of the motion by using exponentiation, which we can do in javascript using the ** operator.

In this ^ example, we put phase to the power of a positive number above 1 (in this case, 3), which slows down the start of the movement, and speeds up the end of the movement.

If we put phase to the power of a positive number below 1, we get the opposite:

The main problem with using phase ramps in this way, is that they are discontinuous - they jump from the end back to the start in an abrupt fashion.

Triangle Wave

One way of keeping continuity is to use a triangle wave.

A lo-fi way of getting a triangle wave might be to do something like this:

Again, because these signals are between 0-1, we can manipulate them using exponentiation:

Sinusoids

Sinusoids are periodic functions that oscillate smoothly between -1 and 1, and are the result of sine and cosine functions.

The difference between sine and cosine is simply a matter of phase - sine functions begin at 0:

... whereas cosine functions begin at 1:

... which means they are out of phase by 1 / 4 of a phase, which is useful for making things go round in circles:

Envelopes

Often we might want things to happen once and then disappear, rather than continue and repeat. For these cases it can be simpler to think about the way something changes over time as an envelope: