简体   繁体   中英

HSB color fill in JavaScript Canvas

I want to fill some circles with HSL color, such that I can change their brightness value. I am kind of a newb at JavaScript programming and I could not find anything about HSL color in JavaScript. I currently have this code:

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

And I want to basically find an equivalent of the rgb -function, but with HSL.

you can convert from HSV to rgb. In canvas you can use this:

  • Hexadecimal colors: ctx.fillStyle = "#0000FF";
  • RGB Colors: ctx.fillStyle = "RGB(0,0,255)"
  • RGBA Colors: ctx.fillStyle = "RGBA(0,0,255,0.3)";
  • HSL Colors: ctx.fillStyle = "HSL(120,100,50)";
  • HSLA Colors: ctx.fillStyle = "HSLA(120,100,50,0.3)";

A function to convert from hsv to rgba looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM