在 PHP/jQuery 中从十六进制代码或 RGB 生成渐变?
我试图弄清楚如何编写一个函数,以编程方式检索背景颜色 css 属性并创建两个输出(一个比背景颜色稍深,一个比背景颜色稍浅)。
这个想法是能够从单一颜色选择中生成非常基本的线性渐变。
有人有什么想法吗?
I'm trying to figure out how to write a function that programmatically retrieves a background-color css attribute and creates two outputs (one slightly darker than the background-color, one slightly lighter).
The idea is being able to generate a very basic linear gradient from a single color selection.
Anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要正确缩放颜色,必须将每个 RGB 值乘以一个比例。
例如
,如果您的颜色是#00417b
,并且您想要浅125%的颜色,那么您必须执行以下操作:亲自比较结果:深色是
#00417b
,光是#00519A
,尽管将它们描述为rgb(0, 65, 123)
和rgb 是完全有效的 CSS (0, 81, 154)
并且可能也更容易。通过以这种方式缩放颜色,它们将看起来处于相同的饱和度水平,这是简单地添加或减去数字无法实现的。请注意,由于值被限制在 [0, 255],如果您不断改变颜色,然后将它们反馈到此过程中,则可能会破坏有关源颜色中红色、绿色和蓝色比例的信息。因此,请保存原始颜色并尝试每次使用它作为输入。
由于您的问题专门询问了渐变,因此这就是您在两个颜色值之间进行转换的方式:
To scale a color correctly, you have to multiply each RGB value by a proportion.
E.g.
, if your color is#00417b
and you want a color that is 125% lighter color then you have to do this:Compare the result for yourself: dark is
#00417b
, and light is#00519A
, although it's perfectly valid CSS to describe them asrgb(0, 65, 123)
andrgb(0, 81, 154)
and probably easier too. By scaling colors in this way they will appear to be at the same level of saturation, something that simply adding or subtracting numbers will not achieve.Be aware that since values are clamped at [0, 255], if you keep shifting colors, then feeding them back into this process, you can destroy information about the proportion of red, green and blue in the source color. For this reason, keep the original color saved and try to use that as your input each time.
Since your question asked specifically about gradients though, this is how you would go between two color values:
要生成较暗或较亮的 vairant,一种简单的方法就是对所有三个分量添加或减去一个固定数字,将其上限设置为 0 和 255/0xFF。
To generate a darker or lighter vairant, a simple possibility is just to add or subtract a fixed number to all three componenents, capping it at 0 and 255/0xFF.