CSS中的颜色变化
Let’s suppose we’re building this particle effect:
假设我们正在构建这个粒子效果:
This effect is something we build in my upcoming animations course(opens in new tab), and there are lots of little details, but in this blog post, I want to zoom in on one surprisingly-interesting facet: the color shifting.
这个效果是我们在我的 即将推出的动画课程(opens in new tab) 中构建的,还有很多小细节,但在这篇博客文章中,我想聚焦于一个令人惊讶的有趣方面:颜色的变化。
Each particle starts on a random color and changes hue as it fades out. This seems pretty straightforward, but appearances can be deceiving. In fact, I discovered a new CSS limitation I wasn’t aware of, and came up with a couple different workarounds.
每个粒子从随机颜色开始,并在淡出时改变色调。这 看起来 相当简单,但表象可能会欺骗。事实上,我发现了一个我之前不知道的新 CSS 限制,并想出了几种不同的解决方法。
In this tutorial, I’ll share what I’ve learned, and you’ll see how to build some super-cool color-shifting effects in CSS!
在本教程中,我将分享我所学到的内容,您将看到如何在CSS中构建一些超级酷的颜色变化效果!
Intended audience
目标受众
This tutorial was written for developers of all experience levels. If you understand the fundamentals of HTML/CSS/JS, you should be able to follow along!
本教程是为所有经验水平的开发人员编写的。如果您理解HTML/CSS/JS的基本知识,您应该能够跟上!
I do assume some familiarity with the hsl() color format and CSS keyframe animations, but I also have blog posts about both of those topics, and I’ll link them further down as they become relevant.
我假设对 hsl() 颜色格式和 CSS 关键帧动画有一定的熟悉度,但我也有关于这两个主题的博客文章,我会在相关时进一步链接它们。
Link to this headingHello color
链接到这个标题你好,颜色
So, in my particle effect, I want every particle to have its own dynamic colors.
所以,在我的粒子效果中,我希望每个粒子都有自己动态的颜色。
Let’s start with the simplest possible option, generating a random color using RGB values:
让我们从最简单的选项开始,使用 RGB 值生成随机颜色:
// Do this for every particle:
const red = Math.round(Math.random() * 255);
const green = Math.round(Math.random() * 255);
const blue = Math.round(Math.random() * 255);
particle.style.backgroundColor =
`rgb(${red} ${green} ${blue})`;
The RGB color format supports 16.7 million possible colors (2563), and this code will select one of them, totally at random. Here’s what that looks like:
RGB 颜色格式支持 1670 万...