Couleur aléatoire générateur

étant donné cette fonction, je veux remplacer le color par un générateur de couleur aléatoire.

document.overlay = GPolyline.fromEncoded({
    color: "#0000FF",
    weight: 10,
    points: encoded_points,
    zoomFactor: 32,
    levels: encoded_levels,
    numLevels: 4
});

Comment puis-je le faire?

321
demandé sur Narendra Jadhav 2009-09-28 01:17:44

30 réponses

utiliser getRandomColor() au lieu de "#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
répondu Anatoliy 2017-06-23 06:41:26

je doute que quelque chose soit plus rapide ou plus court que celui-ci:

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

Challenge!

207
répondu ZPiDER 2011-03-19 21:47:36

voici un autre point de vue sur ce problème.

mon but était de créer des couleurs vives et distinctes. Pour assurer les couleurs sont distincts-je éviter d'utiliser un générateur aléatoire et sélectionnez "espacé" les couleurs de l'arc-en-ciel.

c'est parfait pour créer des marqueurs pop-out dans Google Maps qui ont une" unicité " optimale (c'est-à-dire qu'aucun deux marqueurs n'aura des couleurs similaires).

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

Si vous voulez voir à quoi cela ressemble comme en action voir http://blog.adamcole.ca/2011/11/simple-javascript-rainbow-color.html .

129
répondu Adam Cole 2015-05-19 05:18:51

Qui peut le battre?

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

garanti pour travailler tout le temps: http://jsbin.com/OjELIfo/2/edit

basé sur @eterps comment le code ci-dessus peut encore générer des chaînes plus courtes si la représentation hexadécimale de la couleur aléatoire est très courte ( 0.730224609375 => 0.baf )

ce code devrait fonctionner dans tous les cas:

function makeRandomColor(){
  var c = '';
  while (c.length < 7) {
    c += (Math.random()).toString(16).substr(-6).substr(-1)
  }
  return '#'+c;
}
41
répondu Mohsen 2015-03-27 19:04:04

il n'y a pas besoin d'un hachage de lettres hexadécimales. JavaScript peut le faire par lui-même:

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
répondu Alsciende 2016-12-29 14:45:26

j'aime celui-ci: '#' + (Math.random().toString(16) + "000000").substring(2,8)

25
répondu Nicolas Buduroi 2016-04-05 21:38:26

génération aléatoire de couleurs avec contrôle de luminosité:

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
répondu letronje 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
répondu jt3k 2015-09-17 13:47:18

vous pouvez aslo utiliser HSL disponible sur chaque bon navigateur ( http://caniuse.com/#feat=css3-colors )

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

cela vous donnera seulement des couleurs vives, vous pouvez aussi jouer avec la luminosité, la saturation et l'alpha.

// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
18
répondu kigiri 2018-09-15 06:28:26

voici un twist sur la solution fournie par @Anatoliy.

j'avais besoin de générer seulement des couleurs claires( pour les fonds), donc j'ai choisi le format à trois lettres (#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
répondu Andrei R 2016-12-29 13:49:35

L'article écrit par Paul Irish sur l'Aléatoire de Couleur Hexadécimale Générateur de Code en JavaScript, c'est absolument incroyable. Use:

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

voici le lien source:

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

14
répondu way2vin 2016-12-29 14:57:43

cela peut être très facilement trouvé en utilisant Google Search:

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, '#');
            break;

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

        default:
            return rint;
            break;
    }
}

mise à Jour de la version:

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
répondu Funky Dude 2017-02-19 11:33:17
var color = "#";
for (k = 0; k < 3; k++) {
    color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}

Une dégradation de la façon dont cela fonctionne:

Math.random()*256 obtient un nombre aléatoire (point flottant) de 0 à 256 (0 à 255 inclusivement)

Exemple de résultat: 116.15200161933899

ajouter le |0 bandes de tout après le point décimal.

Ex: 116.15200161933899 - > 116

par .toString(16) convertit ce nombre en hexadécimal (base 16).

Ex: 116 -> 74

Un autre ex: 228 - > e4

ajout de "0" le tamponne avec un zéro. Cela sera important lorsque nous aurons le substrat, puisque notre résultat final doit avoir deux caractères pour chaque couleur.

Ex: 74 -> 074

Un autre ex: 8 - > 08

.substr(-2) reçoit seulement les deux derniers caractères.

Ex: 074 - > 74

Un autre ex: 08 -> 08 (si nous n'avions pas ajouté le "0" , cela aurait produit " 8 "au lieu de" 08")

la boucle for exécute cette boucle trois fois, en ajoutant chaque résultat à la chaîne de couleur, produisant quelque chose comme ceci:

#7408e4

10
répondu Erin Heyming 2013-10-22 20:01:15

si vous êtes un noob comme moi, ignorant sur les hexadécimaux et autres, cela pourrait être plus intuitif.

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

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

vous avez juste besoin de finir avec une chaîne de caractères comme 'rgb(255, 123, 220)'

9
répondu ICoffeeConsumer 2018-02-11 12:51:30

donc bien que toutes les réponses ici sont bonnes, je voulais un peu plus de contrôle sur la sortie. Par exemple, j'aimerais éviter les teintes presque blanches, tout en m'assurant d'obtenir des couleurs vives vives et non des teintes délavées.

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() +")";
        };

donc maintenant je peux spécifier 3 plages arbitraires pour choisir des valeurs RVB. Vous pouvez l'appeler sans arguments et obtenir mon jeu par défaut qui générera habituellement une couleur très vibrante avec une nuance dominante évidente, ou vous pouvez fournir votre propre tableau des plages.

8
répondu Ollie Edwards 2010-06-24 11:41:34

réponse courte avec tampon à la taille exacte

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

8
répondu Taha Jahangir 2012-03-01 09:06:40

encore un autre générateur de couleur aléatoire:

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
répondu Salman A 2011-07-23 08:29:44

Array.prototype.reduce le rend très propre.

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

a besoin d'une minuterie pour les vieux navigateurs.

6
répondu user1106925 2013-05-16 21:28:56

vous pouvez utiliser cette fonction simple

function getRandomColor(){
 var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
 return color;
}
6
répondu ChandrasekarG 2016-08-22 11:41:36

le commentaire voté en haut de la réponse suggère que L'approche de Martin Ankerl est meilleure que les nombres hexadécimaux aléatoires, et bien que je n'ai pas amélioré la méthodologie D'Ankerl, Je l'ai traduit avec succès en JavaScript. J'ai pensé que je posterais une réponse supplémentaire à ce fil déjà méga-dimensionné parce que la réponse du haut a un autre commentaire reliant à un Gist avec l'implémentation JS de la logique D'Ankerl et ce lien est cassé (404). Si j'avais la réputation, j'aurais tout simplement commente le lien jsbin que j'ai créé.

// 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
répondu spakmad 2017-05-06 00:31:09

version ES6.

couleur Aléatoire

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

Alpha Aléatoire, Couleur aléatoire.

`#${Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, 0)}`
6
répondu K._ 2017-11-10 22:15:35
function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}

http://jsfiddle.net/XmqDz/1 /

5
répondu 2013-08-13 14:35:36

Utiliser distinctes-couleurs .

il génère une palette de visuellement couleurs distinctes.

distinct-couleurs est hautement configurable:

  • choisissez combien de couleurs sont dans la palette
  • restreindre la teinte à une plage spécifique
  • restreindre le chroma (saturation) à une plage spécifique
  • Limiter la légèreté à une plage spécifique
  • configurer la qualité générale de la palette
5
répondu InternalFX 2015-08-20 17:23:42

Voici mes deux versions pour un générateur de code hexadécimal aléatoire.


/* 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
répondu Larry Battle 2011-01-24 04:05:18

cette fonction va au-delà des autres réponses de deux façons:

il tente de générer des couleurs aussi distinctes que possible en trouvant quelle couleur sur 20 essais a la plus loin distance euclidienne de les autres dans le cône HSV

il vous permet de restreindre la teinte, saturation, ou gamme de valeurs, mais tente toujours de choisir des couleurs comme distinctes que possible à l'intérieur de cette gamme.

ce n'est pas super efficace, mais pour des valeurs raisonnables (qui pourrait même démonter 100 couleurs facilement?) Il est assez rapide.

Voir 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
répondu Andy 2015-06-08 21:06:07

presque toutes les méthodes à main courte précédentes génèrent des codes hexadécimaux invalides (cinq chiffres). Je suis tombé sur une technique similaire que sans cette question ici :

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

Test

essayez ceci dans la console:

for(i = 0; i < 200; i++) {
    console.log("#" + ("000" + (Math.random()*(1<<24)|0).toString(16)).substr(-6));
}
3
répondu manikanta 2016-12-29 14:49:37

Il y a tellement de façons que vous pouvez accomplir cela. J'en ai fait deux:

génère six nombres hexadécimaux aléatoires (0-F)

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

génère des composants RVB individuels (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
répondu bryc 2012-11-27 23:37:35

vous pouvez utiliser colorchain.js pour générer une séquence de couleurs avec des teintes variables.

2
répondu alexishacks 2014-07-28 07:28:54

cette méthode obtiendra un nombre aléatoire, le convertira en chaîne hexidécimale et en extraira une partie, vous donnant un hexadécimal aléatoire.

function randomColor() {
    return "#" + Math.random().toString(16).slice(2,8);
}
2
répondu Anish Kasam 2016-05-27 07:32:32

ma version:

function RandomColor() {
  var hex = (Math.round(Math.random()*0xffffff)).toString(16);
  while (hex.length < 6) hex = "0" + hex;
  return hex;
}
2
répondu Prostakov 2016-12-29 14:50:12