Skip to content

Instantly share code, notes, and snippets.

@bendc
Last active February 7, 2024 03:19
Show Gist options
  • Save bendc/76c48ce53299e6078a76 to your computer and use it in GitHub Desktop.
Save bendc/76c48ce53299e6078a76 to your computer and use it in GitHub Desktop.
Generate nice random colors
const randomColor = (() => {
"use strict";
const randomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
return () => {
var h = randomInt(0, 360);
var s = randomInt(42, 98);
var l = randomInt(40, 90);
return `hsl(${h},${s}%,${l}%)`;
};
})();
@mevin-g
Copy link

mevin-g commented Mar 10, 2021

This is really nice!

@Park-Joyeong
Copy link

Thank you :D

@helloworldwriter
Copy link

First of all, thanks for the function. I'm trying it in Dart (Flutter), in this CodePen.

Generating random colors by just using Math.random values often results in dark and unattractive colors. The randomColor function applies some restrictions in order to return more vibrant and appealing colors.

Just curious, the values of the restrictions (42, 98, etc.) - how did you select them?

An example of use can be seen on this demo.

The url of the demo no longer works.

@bendc
Copy link
Author

bendc commented Jun 7, 2022

First of all, thanks for the function. I'm trying it in Dart (Flutter), in this CodePen.

Generating random colors by just using Math.random values often results in dark and unattractive colors. The randomColor function applies some restrictions in order to return more vibrant and appealing colors.

Just curious, the values of the restrictions (42, 98, etc.) - how did you select them?

I eyeballed them -- feel free to tweak them!

An example of use can be seen on this demo.

The url of the demo no longer works.

Here you are :)

@ethndotsh
Copy link

How could I use a seed to generate the same color with the same input, but still have it be nice and vibrant?

@ianthedev
Copy link

Thanks for the snippet. Is there a version for directly generating the hex format instead of the hsl format? I need to apply the generated colors on <input type="color">, which only accepts the hex format.

I can probably add a "hsl to hex" function into the snippet, but that would make the snippet unnecessarily longer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment