怎么只在JavaScript中生成随机颜色? [英] how generate only darken random colors in javascript?

查看:325
本文介绍了怎么只在JavaScript中生成随机颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里阅读关于如何在JS / JQuery中生成随机颜色的问题。但我想只产生黑色,避免黑色,黄色和灰色范围颜色,以便能够绘制不同颜色的谷歌地图区域。

I've been reading the questions here about how to generate random colors in JS/JQuery. But I want to generate only darken colors avoiding the black, yellow and gray range colors, in order to be able to draw areas in google maps with different colors.

谢谢

推荐答案

var hue = Math.floor(Math.random() * 360),
    saturation =  Math.floor(Math.random() * 100),
    lightness =  Math.floor(Math.random() * 50),
    color = "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";

这是为了生成随机hsl颜色。但是,如果你想变暗现有的rgb颜色,最好的做法是将其转换为hsl,然后根据你的需要设置其亮度值。有这些函数的乐趣:

That was to generate a random hsl color. But if you want to darken an existing rgb color the best thing to do is to convert it to hsl and then setting its lightness value according to your needs. Have fun with these functions:

function rgbToHsl(r, g, b) {
    var maxRGB = Math.max(r, g, b),
        minRGB = Math.min(r, g, b),
        tmp, h, s, l;
    tmp = maxRGB - minRGB;
    l = (maxRGB + minRGB)/255;
    if (tmp) {
        s = Math.round(tmp/(l < 1 ? l : 2 - l))/255;
        if (r === maxRGB) h = (g - b)/tmp;
        else if (g === maxRGB) h = 2 + (b - r)/tmp;
        else h = 4 + (r - g)/tmp;
        h = (h < 0 ? h + 6 : h)*60 % 360;
    } else h = s = 0;
    l /= 2;
    return [h, s, l];
}
function hslToRgb(h, s, l) {
    if (!s) return r = g = b = l*255;
    var q = l < .5 ? l*(1 + s) : l + s - l*s,
        p = 2*l - q;

    for (var i = 120, t, c = []; i >= -120; i -= 120) {
        t = h + i;
        if (t < 0) t += 360;
        else if (t >= 360) t -= 360;
        if (t < 60) c.push(p + (q - p)*t/60);
        else if (t < 180) c.push(q);
        else if (t < 240) c.push(p + (q - p)*(240 - t)/60);
        else c.push(p);
    }
    return [c[0]*255, c[1]*255, c[2]*255];
}

这里, s l 范围从 0 1 r g b / code>到 0 255 h >到 359

Here, s and l ranges from 0 to 1, r, g and b from 0 to 255 and h from 0 to 359.

这篇关于怎么只在JavaScript中生成随机颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆