我想用HSL颜色填充一些圆圈,这样我就可以改变它们的亮度值。 我是 JavaScript 编程的新手,我在 JavaScript 中找不到任何有关 HSL 颜色的信息。 我目前有这个代码:
context.fillStyle = 'rgb(200, 100, 0)';
我基本上想找到
rgb
函数的等价物,但是使用 HSL。
您可以从 HSV 转换为 RGB。 在画布中你可以使用这个:
ctx.fillStyle = "#0000FF";
ctx.fillStyle = "RGB(0,0,255)"
ctx.fillStyle = "RGBA(0,0,255,0.3)";
ctx.fillStyle = "HSL(120,100,50)";
ctx.fillStyle = "HSLA(120,100,50,0.3)";
从 hsv 转换为 rgba 的函数如下所示:
function HSVtoRGB(h, s, v) {
var r, g, b, i, f, p, q, t;
if (arguments.length === 1) {
s = h.s, v = h.v, h = h.h;
}
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}
我写了一个有助于颜色转换的包:
它使您能够解析/转换大多数颜色格式:
import {Color} from 'modern-color';
let c = Color.parse('rgb(200, 100, 0)');
let hsl = c.hsl;
for (let h = 0; h < 360; h += 24){
hsl.h = h;
console.log(hsl, Color.parse(hsl));
}
实际上是专为这个确切的用例而设计的!您可以以相同的方式遍历任何颜色通道并在画布中制作很酷的效果。