Helder Esteves

Type and hit Enter to search

JavaScript
Uncategorized
Software Architecture
React
General
Management
Next.JS
TypeScript
JavaScript
Uncategorized
Software Architecture
React
General
Management
Next.JS
TypeScript
JavaScript

Generating Random Colors in JS + Dark, Light colors

Helder Esteves
Helder Esteves
February 18, 2023 4 Mins Read
90 Views
0 Comments

Generating random colors in JS easily with all representations.

Generating random colors — HEX

function generateRandomColorHex() {
  return "#" + ("00000" + Math.floor(Math.random() * Math.pow(16, 6)).toString(16)).slice(-6);
}

Example generated color: #958e00

Explanation

Color hexes range from #000000 (black) to #FFFFFF (white). In decimal, 0xFFFFFF is equal to 16⁶ -1. This is the maximum value a HEX color can have.

Like many solutions suggest around the internet, the easiest way is to randomize a decimal number and convert it back to a hex value, however, it’s possible to produce an invalid color if you’re not careful.

This is why we pad the random HEX number with “00000” at the start, since Math.floor(Math.random() * Math.pow(16, 6)).toString(16) may produce HEX numbers with less than 6 digits (in the worst case, “0”).

We then slice out the last 6 digits as required by the color hex to get what we want. There are other shorter solutions using ES6, but this works across all browsers.

Generating random colors — RGB

function generateRandomColorRgb() {
  const red = Math.floor(Math.random() * 256);
  const green = Math.floor(Math.random() * 256);
  const blue = Math.floor(Math.random() * 256);
  return "rgb(" + red + ", " + green + ", " + blue + ")";
}

Example generated color: rgb(65, 170, 178)

Explanation

Both color hexes and R G B values are a combination of red (R), green (G), and blue (B). Each primary color can range from 0 to 255 values.

Here, all we need to do is randomize each primary color, floor it to stay within range, then add everything together.

Generating random colors — HSL

function generateRandomColorHsl() {
  const hue = Math.floor(Math.random() * 360);
  const saturation = Math.floor(Math.random() * (100 + 1)) + "%";
  const lightness = Math.floor(Math.random() * (100 + 1)) + "%";
  return "hsl(" + hue + ", " + saturation + ", " + lightness + ")";
}

Example generated color: hsl(78, 96%, 32%)

Explanation

HSL representation uses the hue which ranges from 0 to 359 (angle in the color wheel), saturation which ranges from 0 to 100%, and lightness which also ranges from 0 to 100%

The code above implements the random values for each parameter. For saturation and lightness, we do 100 + 1 because the value can be 100%. You could also do Math.round(Math.random() * 100), but the values 0 and 100 wouldn’t have the same probability as the numbers in-between.

Generating random dark colors

HEX

function generateDarkColorHex() {
  let color = "#";
  for (let i = 0; i < 3; i++)
    color += ("0" + Math.floor(Math.random() * Math.pow(16, 2) / 2).toString(16)).slice(-2);
  return color;
}

Example generated color: #7e5e3a

RGB

function generateDarkColorRgb() {
  const red = Math.floor(Math.random() * 256/2);
  const green = Math.floor(Math.random() * 256/2);
  const blue = Math.floor(Math.random() * 256/2);
  return "rgb(" + red + ", " + green + ", " + blue + ")";
}

Example generated color: rgb(23, 5, 95)

HSL

function generateDarkColorHsl() {
  const hue = Math.floor(Math.random() * 360);
  const saturation = Math.floor(Math.random() * (100 + 1)) + "%";
  const lightness = Math.floor(Math.random() * (100/2 + 1)) + "%";
  return "hsl(" + hue + ", " + saturation + ", " + lightness + ")";
}

Example generated color: hsl(340, 48%, 23%)

Explanation

As mentioned before, both HEX and RGB colors are an addition of red, green, and blue (primary colors). In rgb() function, each color is explicitly written with a decimal value, however, in HEX, it follows the pattern: #FF FF FF (that’s why #FF0000 is red, #00FF00 is green, and #0000FF is blue). Once again, each primary color ranges from 0 to 255 (16² -1) for both cases.

In these colors, 0 is dark and 255 is the lightest. We can now use this information to build the functions, as we just need to randomize each color up to 16²/2.

For HSL representation, we simply limit the last parameter (lightness) to 100%/2. Easy enough, right?

Generating random light colors

HEX

function generateLightColorHex() {
  let color = "#";
  for (let i = 0; i < 3; i++)
    color += ("0" + Math.floor(((1 + Math.random()) * Math.pow(16, 2)) / 2).toString(16)).slice(-2);
  return color;
}

Example generated color: #acdddf

RGB

function generateLightColorRgb() {
  const red = Math.floor((1 + Math.random()) * 256/2);
  const green = Math.floor((1 + Math.random()) * 256/2);
  const blue = Math.floor((1 + Math.random()) * 256/2);
  return "rgb(" + red + ", " + green + ", " + blue + ")";
}

Example generated color: rgb(233, 166, 149)

HSL

function generateLightColorHsl() {
  const hue = Math.floor(Math.random() * 360);
  const saturation = Math.floor(Math.random() * (100 + 1)) + "%";
  const lightness = Math.floor((1 + Math.random()) * (100/2 + 1)) + "%";
  return "hsl(" + hue + ", " + saturation + ", " + lightness + ")";
}

Example generated color: hsl(302, 97%, 77%)

Explanation

If you managed to follow along with the explanation with the dark colors, it’s analogous for light colors. The only difference here is, we want the colors to fall in the second half of each parameter.

Hence, instead of Math.random(), we do (1 + Math.random()).


As always, if you have any questions, I’ll be sure to reply to them!

Tags:

Beginner

Share Article

Other Articles

Previous

Fetching in JavaScript: The Definitive Guide

Next

Simple Backgrounds For Websites — Cheat Sheet

Next
February 21, 2023

Simple Backgrounds For Websites — Cheat Sheet

Previews
February 15, 2023

Fetching in JavaScript: The Definitive Guide

No Comment! Be the first one.

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Subscribe
    Stay Updated!
    Get notified when awesome content is posted. Learn more everyday.
    Most Read
    Software Architecture
    5 JS Design Patterns Every Developer Should Know
    March 10, 2023
    5 Min Read
    yellow line on gray asphalt road
    Next.JS
    5 Next.JS Tips You Never Heard About
    March 27, 2023
    4 Min Read
    blue UTP cord
    Uncategorized
    Setting up a TURN server with Node: Production-ready
    May 19, 2023
    5 Min Read
    Most Engagement
    brown rope on black background
    Uncategorized
    The Crash Course on Node Redis

    Learn everything you need to know for Node Redis! The only article you'll need to read, from...

    March 3, 2023
    4 Min Read
    Most Recent
    grayscale photo of person holding glass
    JavaScript
    Top 10 JavaScript Coding Challenges You Must Absolutely Know
    May 17, 2023
    9 Min Read
    a person pointing at a rock with writing on it
    JavaScript
    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    5 Min Read
    blue UTP cord
    Uncategorized
    Setting up a TURN server with Node: Production-ready
    May 19, 2023
    5 Min Read

    Related Posts

    yellow line on gray asphalt road
    Next.JS
    5 Next.JS Tips You Never Heard About
    March 27, 2023
    4 Min Read
    Read More
    a person pointing at a rock with writing on it
    JavaScript
    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    5 Min Read
    Read More
    person using black and red Acer laptop computer on table
    Management
    8 Advanced Techniques for Effective Code Review
    April 26, 2023
    4 Min Read
    Read More
    red Wrong Way signage on road
    TypeScript
    Top 7 TypeScript Mistakes You Need to Avoid
    April 26, 2023
    5 Min Read
    Read More

    Helder Esteves

    Read everything there is to know about the JavaScript development ecosystem, from programming to project management.

    Recent

    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    Setting up a TURN server with Node: Production-ready
    May 19, 2023

    Categories

    JavaScript9
    Uncategorized4
    Software Architecture2
    React2

    Contact

    Reach out to us through helder.writer@gmail.com

    © 2022, All Rights Reserved.

    Go to mobile version