css 颜色转换背后的数学原理是什么?

What's the math behind css transitions on colours?

如果我有这个代码:

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

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

如果我将鼠标悬停在元素上,颜色会在 10 秒内从蓝色平滑过渡到红色。

如果有时间线:

0 seconds - Blue

5 seconds - ?

10 seconds - Red

有没有一种方法可以计算过渡中 5 秒或任意秒数的颜色?

由none而不是transition-timing-function property决定,它可以用三次贝塞尔曲线表示,也可以用与预定义曲线对应的预定义关键字来表示。在您的示例中,此 属性 的值为 linear,因此在 5 秒间隔内,该值将恰好是开始值和结束值的平均值。

该规范还定义了 interpolated 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).

您可以使用 window.getComputedStyle() 等获取正在进行的转换期间任何给定时间点的精确值。来自 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.