Generator losowych kolorów

Biorąc pod uwagę tę funkcję, chcę zastąpić kolor generatorem losowych kolorów.

document.overlay = GPolyline.fromEncoded({
    color: "#0000FF",
    weight: 10,
    points: encoded_points,
    zoomFactor: 32,
    levels: encoded_levels,
    numLevels: 4
});
Jak mogę to zrobić?
Author: Narendra Jadhav, 2009-09-28

30 answers

Użycie getRandomColor() zamiast "#0000FF":

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}



function setRandomColor() {
  $("#colorpad").css("background-color", getRandomColor());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="colorpad" style="width:300px;height:300px;background-color:#000">

</div>
<button onclick="setRandomColor()">Random Color</button>
 773
Author: Anatoliy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-23 06:41:26

Wątpię, żeby cokolwiek było szybsze lub krótsze od tego:

"#"+((1<<24)*Math.random()|0).toString(16)
Wyzwanie!
 207
Author: ZPiDER,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-19 21:47:36

Oto kolejne ujęcie tego problemu.

Moim celem było stworzenie żywych i wyrazistych kolorów. Aby upewnić się, że kolory są wyraźne, unikam używania generatora losowego i wybieram "równomiernie rozmieszczone" kolory z tęczy.

Jest to idealne rozwiązanie do tworzenia znaczników wyskakujących w Google Maps, które mają optymalną "wyjątkowość" (czyli żadne dwa znaczniki nie będą miały podobnych kolorów).

function rainbow(numOfSteps, step) {
    // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.
    // Adam Cole, 2011-Sept-14
    // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
    var r, g, b;
    var h = step / numOfSteps;
    var i = ~~(h * 6);
    var f = h * 6 - i;
    var q = 1 - f;
    switch(i % 6){
        case 0: r = 1; g = f; b = 0; break;
        case 1: r = q; g = 1; b = 0; break;
        case 2: r = 0; g = 1; b = f; break;
        case 3: r = 0; g = q; b = 1; break;
        case 4: r = f; g = 0; b = 1; break;
        case 5: r = 1; g = 0; b = q; break;
    }
    var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
    return (c);
}

Jeśli chcesz zobaczyć jak to wygląda w akcji zobacz http://blog.adamcole.ca/2011/11/simple-javascript-rainbow-color.html .

 129
Author: Adam Cole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-19 05:18:51

Kto może to pokonać?

'#'+Math.random().toString(16).substr(-6);

Gwarantowana praca przez cały czas: http://jsbin.com/OjELIfo/2/edit

Na podstawie komentarza @ eterps powyższy kod może nadal generować krótsze ciągi znaków, jeśli szesnastkowa reprezentacja losowego koloru jest bardzo krótka (0.730224609375 => 0.baf)

Ten kod powinien działać we wszystkich przypadkach:

function makeRandomColor(){
  var c = '';
  while (c.length < 7) {
    c += (Math.random()).toString(16).substr(-6).substr(-1)
  }
  return '#'+c;
}
 41
Author: Mohsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 19:04:04

Nie ma potrzeby stosowania skrótu szesnastkowego. JavaScript może to zrobić Sam:

function get_random_color() {
  function c() {
    var hex = Math.floor(Math.random()*256).toString(16);
    return ("0"+String(hex)).substr(-2); // pad with zero
  }
  return "#"+c()+c()+c();
}
 26
Author: Alsciende,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 14:45:26

Podoba mi się ten: '#' + (Math.random().toString(16) + "000000").substring(2,8)

 25
Author: Nicolas Buduroi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-05 21:38:26

Losowe generowanie kolorów z regulacją jasności:

function getRandColor(brightness){

    // Six levels of brightness from 0 to 5, 0 being the darkest
    var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
    var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
    var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
    return "rgb(" + mixedrgb.join(",") + ")";
}
 25
Author: letronje,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 14:47:03
'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123
 18
Author: jt3k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-17 13:47:18

Możesz również używać HSL dostępnego w każdej dobrej przeglądarce ( http://caniuse.com/#feat=css3-colors )

function randomHsl() {
    return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}

To daje tylko jasne kolory, można również bawić się z jasnością, nasyceniem i Alfa.

// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
 18
Author: kigiri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-15 06:28:26

Oto zwrot na rozwiązanie dostarczone przez @ Anatoliy.

Musiałem wygenerować tylko jasne kolory (dla tła), więc wybrałem format trzyliterowy (#AAA):

function get_random_color() {
    var letters = 'ABCDE'.split('');
    var color = '#';
    for (var i=0; i<3; i++ ) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;
}
 14
Author: Andrei R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 13:49:35

Artykuł napisany przez Paul Irish Na Random Hex Color Code Generator w JavaScript jest absolutnie niesamowity. Użycie:

'#'+Math.floor(Math.random()*16777215).toString(16);

Oto link źródłowy:

Http://www.paulirish.com/2009/random-hex-color-code-snippets/

 14
Author: way2vin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 14:57:43

Można to bardzo łatwo znaleźć za pomocą wyszukiwarki Google:

function random_color(format)
{
    var rint = Math.round(0xffffff * Math.random());
    switch(format)
    {
        case 'hex':
            return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
            break;

        case 'rgb':
            return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
            break;

        default:
            return rint;
            break;
    }
}

Wersja zaktualizowana:

function random_color( format ){
  var rint = Math.floor( 0x100000000 * Math.random());
  switch( format ){
    case 'hex':
      return '#' + ('00000'   + rint.toString(16)).slice(-6).toUpperCase();
    case 'hexa':
      return '#' + ('0000000' + rint.toString(16)).slice(-8).toUpperCase();
    case 'rgb':
      return 'rgb('  + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ')';
    case 'rgba':
      return 'rgba(' + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ',' + (rint >> 24 & 255)/255 + ')';
    default:
      return rint;
  }
}
 13
Author: Funky Dude,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-19 11:33:17
var color = "#";
for (k = 0; k < 3; k++) {
    color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}

Podział jak to działa:

Math.random()*256 pobiera losową (zmiennoprzecinkową) liczbę od 0 do 256 (0 do 255 włącznie)
Przykładowy wynik: 116.15200161933899

Dodanie |0 usuwa wszystko po przecinku.
Ex: 116.15200161933899 - > 116

Using .toString(16) converts this number to hexadecimal (base 16).
Ex: 116 - > 74
Inny ex: 228 - > e4

Dodanie "0" oznacza zero. Będzie to ważne, gdy otrzymamy podłańcuch, ponieważ nasz wynik końcowy musi mieć dwa znaki dla każdego koloru.
Ex: 74 - > 074
Inny ex: 8 - > 08

.substr(-2) dostaje tylko dwa ostatnie znaki.
Ex: 074 - > 74
Inne ex: 08 - > 08 (gdybyśmy nie dodali "0", wytworzylibyśmy "8" zamiast "08")

Pętla for uruchamia tę pętlę trzy razy, dodając każdy wynik do ciągu kolorów, tworząc coś takiego:
#7408e4

 10
Author: Erin Heyming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-22 20:01:15

Jeśli jesteś noobem takim jak ja, nie masz pojęcia o szesnastkach i tym podobnych, może to być bardziej intuicyjne.

function r() { return Math.floor(Math.random() * 255) }

var color = 'rgb(' + r() + "," + r() + "," + r() + ')';

Wystarczy skończyć z ciągiem takim jak 'rgb(255, 123, 220)'

 9
Author: ICoffeeConsumer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-11 12:51:30

Więc chociaż wszystkie odpowiedzi tutaj są dobre, chciałem trochę więcej kontroli nad wyjściem. Na przykład chciałbym zapobiec prawie białym odcieniom, zapewniając jednocześnie jasne żywe kolory, a nie wyprane odcienie.

function generateColor(ranges) {
            if (!ranges) {
                ranges = [
                    [150,256],
                    [0, 190],
                    [0, 30]
                ];
            }
            var g = function() {
                //select random range and remove
                var range = ranges.splice(Math.floor(Math.random()*ranges.length), 1)[0];
                //pick a random number from within the range
                return Math.floor(Math.random() * (range[1] - range[0])) + range[0];
            }
            return "rgb(" + g() + "," + g() + "," + g() +")";
        };

Więc teraz mogę określić 3 dowolne zakresy, z których można wybrać wartości rgb. Możesz wywołać go bez argumentów i uzyskać mój domyślny zestaw, który zwykle generuje dość żywy kolor z oczywistym dominującym odcieniem, lub możesz podać własną tablicę zakresów.

 8
Author: Ollie Edwards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-24 11:41:34

Krótka odpowiedź z podkładką do dokładnego rozmiaru

'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)

 8
Author: Taha Jahangir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-01 09:06:40

Kolejny generator losowych kolorów:

var randomColor;
randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000 (randomColor is a float)
randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF (randomColor is an integer)
randomColor = randomColor.toString(16); // hex representation randomColor
randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
randomColor = "#" + randomColor; // # added
 6
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-23 08:29:44

Array.prototype.reduce sprawia, że jest bardzo czysty.

["r","g","b"].reduce(function(res) {
    return res + ("0"+~~(Math.random()*256).toString(16)).slice(-2)
}, "#")

Potrzebuje shim dla starych przeglądarek.

 6
Author: user1106925,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-16 21:28:56

Możesz użyć tej prostej funkcji

function getRandomColor(){
 var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
 return color;
}
 6
Author: ChandrasekarG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-22 11:41:36

Głosowany komentarz top answer sugeruje, że podejście Martina Ankerla jest lepsze niż przypadkowe liczby szesnastkowe i chociaż nie poprawiłem metodologii Ankerla, z powodzeniem przetłumaczyłem ją na JavaScript. Pomyślałem, że wrzucę dodatkową odpowiedź do tego już mega dużego wątku, bo w górnej odpowiedzi jest jeszcze komentarz linkujący do Gista z implementacją JS logiki Ankerla i ten link jest zepsuty (404). Gdybym miał taką reputację, po prostu skomentowałbym łącze jsbin, które stworzyłem.

// adapted from
// http://jsfiddle.net/Mottie/xcqpF/1/light/
const rgb2hex = (rgb) => {
 return (rgb && rgb.length === 3) ? "#" +
  ("0" + parseInt(rgb[0],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) : '';
}

// next two methods converted from Ruby to JS
// soured from http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

// # HSV values in [0..1[
// # returns [r, g, b] values from 0 to 255
const hsv_to_rgb = (h, s, v) => {
  const h_i = Math.floor(h*6)
  const f = h*6 - h_i
  const p = v * (1 - s)
  const q = v * (1 - (f * s))
  const t = v * (1 - (1 - f) * s)
  let r, g, b
  switch(h_i){
    case(0):
      [r, g, b] = [v, t, p]
      break
    case(1):
      [r, g, b] = [q, v, p]
      break
    case(2):
      [r, g, b] = [p, v, t]
      break
    case(3):
      [r, g, b] = [p, q, v]
      break
    case(4):
      [r, g, b] = [t, p, v]
      break
    case(5):
      [r, g, b] = [v, p, q]
      break
  }
  return [Math.floor(r * 256), Math.floor(g * 256), Math.floor(b * 256)]
}

// # use golden ratio
const golden_ratio_conjugate = 0.618033988749895
let h = Math.random() // # use random start value
const gen_hex = (numberOfColors) => {
  const colorArray = []
  while (numberOfColors > 0) {
    h += golden_ratio_conjugate
    h %= 1
    colorArray.push(rgb2hex(hsv_to_rgb(h, 0.99, 0.99)))
    numberOfColors -= 1
  }
  console.log(colorArray)
  return colorArray
}

gen_hex(100)

Https://jsbin.com/qeyevoj/edit?js, console

 6
Author: spakmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-06 00:31:09

Wersja ES6.

Losowy kolor

`#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)}`

Losowa Alfa, losowy kolor.

`#${Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, 0)}`
 6
Author: K._,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-10 22:15:35
function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}

Http://jsfiddle.net/XmqDz/1/

 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-13 14:35:36

Użyj distinct-colors.

Generuje paletę wizualnie różnych kolorów.

Distinct-colors jest wysoce konfigurowalny:

  • Wybierz ile kolorów znajduje się w palecie
  • Ogranicz odcień do określonego zakresu
  • Ogranicz chroma (nasycenie) do określonego zakresu
  • Ogranicz lekkość do określonego zakresu
  • Konfiguracja ogólnej jakości palety
 5
Author: InternalFX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-20 17:23:42

Oto moje dwie wersje generatora kodów sześciokątnych.


/* Slowest but shortest. */
"#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});    

/* Good performance with small size. */
"#"+(function(a,b){while(a--){b+=""+(~~(Math.random()*16)).toString(16);} return b;})(6,"");

/* Remy Sharp provided one that's the fastest but a little bit too long */
(function(h){return '#000000'.substr(0,7-h.length)+h})((~~(Math.random()*(1<<24))).toString(16))

 3
Author: Larry Battle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-24 04:05:18

Ta funkcja wykracza poza inne odpowiedzi na dwa sposoby:

Próbuje wygenerować kolory jak najbardziej wyraziste, znajdując który kolor z 20 prób ma najdalszą odległość od pozostałe w stożku HSV

Pozwala ograniczyć odcień, nasycenia lub zakresu wartości, ale nadal próbuje wybrać kolory jako jak najbardziej w tym zakresie.

Nie jest super wydajny, ale za rozsądne wartości (kto mógłby nawet wybrać 100 kolorów łatwo? Jest wystarczająco szybki.

Zobacz JSFiddle

  /**
   * Generates a random palette of HSV colors.  Attempts to pick colors
   * that are as distinct as possible within the desired HSV range.
   *
   * @param {number}    [options.numColors=10] - the number of colors to generate
   * @param {number[]}  [options.hRange=[0,1]] - the maximum range for generated hue
   * @param {number[]}  [options.sRange=[0,1]] - the maximum range for generated saturation
   * @param {number[]}  [options.vRange=[0,1]] - the maximum range for generated value
   * @param {number[][]}[options.exclude=[[0,0,0],[0,0,1]]] - colors to exclude
   * 
   * @returns {number[][]} an array of HSV colors (each HSV color 
   * is a [hue, saturation, value] array)
   */
  function randomHSVPalette(options) {
    function random(min, max) {
      return min + Math.random() * (max - min);
    } 

    function HSVtoXYZ(hsv) {
      var h = hsv[0];
      var s = hsv[1];
      var v = hsv[2];
      var angle = h * Math.PI * 2;
      return [Math.sin(angle) * s * v,
              Math.cos(angle) * s * v,
              v];
    }

    function distSq(a, b) {
      var dx = a[0] - b[0];
      var dy = a[1] - b[1];
      var dz = a[2] - b[2];
      return dx * dx + dy * dy + dz * dz;
    }

    if (!options) {
      options = {};
    }

    var numColors = options.numColors || 10;
    var hRange = options.hRange || [0, 1];
    var sRange = options.sRange || [0, 1];
    var vRange = options.vRange || [0, 1];
    var exclude = options.exclude || [[0, 0, 0], [0, 0, 1]];

    var points = exclude.map(HSVtoXYZ);
    var result = [];

    while (result.length < numColors) {
      var bestHSV;
      var bestXYZ;
      var bestDist = 0;
      for (var i = 0; i < 20; i++) {
        var hsv = [random(hRange[0], hRange[1]), random(sRange[0], sRange[1]), random(vRange[0], vRange[1])];
        var xyz = HSVtoXYZ(hsv);
        var minDist = 10;
        points.forEach(function(point) {
          minDist = Math.min(minDist, distSq(xyz, point));
        });
        if (minDist > bestDist) {
          bestHSV = hsv;
          bestXYZ = xyz;
          bestDist = minDist;
        }
      }
      points.push(bestXYZ);
      result.push(bestHSV);
    }

    return result;
  }

  function HSVtoRGB(hsv) {
    var h = hsv[0];
    var s = hsv[1];
    var v = hsv[2];

    var i = ~~(h * 6);
    var f = h * 6 - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);
    v = ~~(255 * v);
    p = ~~(255 * p);
    q = ~~(255 * q); 
    t = ~~(255 * t);
    switch (i % 6) {
      case 0: return [v, t, p];
      case 1: return [q, v, p];
      case 2: return [p, v, t];
      case 3: return [p, q, v];
      case 4: return [t, p, v];
      case 5: return [v, p, q];
    }
  }

  function RGBtoCSS(rgb) {
    var r = rgb[0];
    var g = rgb[1];
    var b = rgb[2];
    var rgb = (r << 16) + (g << 8) + b;
    return '#' + ('000000' + rgb.toString(16)).slice(-6);
  }
 3
Author: Andy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-08 21:06:07

Prawie wszystkie poprzednie metody krótkiej ręki generują nieprawidłowe kody szesnastkowe (pięć cyfr). Natknąłem się na podobną technikę tylko bez tego problemu TUTAJ :

"#"+("000"+(Math.random()*(1<<24)|0).toString(16)).substr(-6)

Test

Spróbuj tego w konsoli:

for(i = 0; i < 200; i++) {
    console.log("#" + ("000" + (Math.random()*(1<<24)|0).toString(16)).substr(-6));
}
 3
Author: manikanta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 14:49:37

Jest tak wiele sposobów, aby to osiągnąć. Oto dwa zrobiłem:

Generuje sześć losowych cyfr szesnastkowych (0-F)

function randColor() {
    for (var i=0, col=''; i<6; i++) {
        col += (Math.random()*16|0).toString(16);
    }
    return '#'+col;
}

Generuje poszczególne komponenty RGB (00-FF)

function randColor2() {
    var r = ('0'+(Math.random()*256|0).toString(16)).slice(-2),
        g = ('0'+(Math.random()*256|0).toString(16)).slice(-2),
        b = ('0'+(Math.random()*256|0).toString(16)).slice(-2);
    return '#' +r+g+b;
}
 2
Author: bryc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-27 23:37:35

Możesz użyć colorchain.js do generowania sekwencji kolorów o różnych odcieniach.

 2
Author: alexishacks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-28 07:28:54

Ta metoda uzyska losową liczbę, skonwertuje ją na sześciocyfrowy ciąg znaków, a następnie wyodrębni jego część, dając losowy sześciokąt.

function randomColor() {
    return "#" + Math.random().toString(16).slice(2,8);
}
 2
Author: Anish Kasam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-27 07:32:32

Moja Wersja:

function RandomColor() {
  var hex = (Math.round(Math.random()*0xffffff)).toString(16);
  while (hex.length < 6) hex = "0" + hex;
  return hex;
}
 2
Author: Prostakov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-29 14:50:12