Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the math behind css transitions on colours?

If I have this code:

.box {
    color: #3399FF /* Blue */
    transition: 10s all linear;
}

.box:hover {
    color: #FF3300 /* Red */
}

If I hover on the element the colour will change from Blue to Red over 10 seconds in a smooth transition.

If there was a timeline:

0 seconds - Blue

5 seconds - ?

10 seconds - Red

Is there a way of calculating what the colour will be 5 seconds or any number of seconds in the transition?

like image 937
Tarang Avatar asked Sep 12 '15 03:09

Tarang


1 Answers

That is determined by none other than the transition-timing-function property, which is represented either by a cubic Bezier curve or by a predefined keyword corresponding to a predefined curve. In your example, the value of this property is linear, so at the 5-second interval the value will be exactly the average of the start and end values.

The spec also defines how interpolated values are calculated during transitions. This is what it says about color values:

  • color: interpolated via red, green, blue and alpha components (treating each as a number, see below). The interpolation is done between premultiplied colors (that is, colors for which the red, green, and blue components specified have been multiplied by the alpha).

You can obtain the precise value at any given point in time during a transition that's in progress using window.getComputedStyle() and the like. From the introductory section:

The computed value of a property transitions over time from the old value to the new value. Therefore if a script queries the computed value of a property (or other data depending on it) as it is transitioning, it will see an intermediate value that represents the current animated value of the property.

like image 175
BoltClock Avatar answered Oct 23 '22 05:10

BoltClock