JavaScript Canvas 中的 HSB 颜色填充

问题描述 投票:0回答:2

我想用HSL颜色填充一些圆圈,这样我就可以改变它们的亮度值。 我是 JavaScript 编程的新手,我在 JavaScript 中找不到任何有关 HSL 颜色的信息。 我目前有这个代码:

context.fillStyle = 'rgb(200, 100, 0)';

我基本上想找到

rgb
函数的等价物,但是使用 HSL。

javascript canvas html5-canvas
2个回答
1
投票

您可以从 HSV 转换为 RGB。 在画布中你可以使用这个:

  • 十六进制颜色:
    ctx.fillStyle = "#0000FF";
  • RGB 颜色:
    ctx.fillStyle = "RGB(0,0,255)"
  • RGBA 颜色:
    ctx.fillStyle = "RGBA(0,0,255,0.3)";
  • HSL 颜色:
    ctx.fillStyle = "HSL(120,100,50)";
  • HSLA 颜色:
    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)
    };
}

0
投票

我写了一个有助于颜色转换的包:

npm 现代色彩

它使您能够解析/转换大多数颜色格式:

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));
}

实际上是专为这个确切的用例而设计的!您可以以相同的方式遍历任何颜色通道并在画布中制作很酷的效果。

© www.soinside.com 2019 - 2024. All rights reserved.