01/03/2023

Generating Random Colors on a Range

If you want to add some visual interest to your website, consider incorporating random colors. While using the Math.random() function to generate colors can be a quick and easy option, it may result in some less-than-appealing hues. An alternative approach is to create a set of random colors that all conform to a specific color profile. Here's a simple method for doing so.

Code

function color(min, max, rng) {
    let c = [min, max, Math.floor(Math.random() * (max - min)) + min].sort(() =>
        Math.random() > 0.5 ? 1 : -1
    );
    return `rgb(${c[0]},${c[1]},${c[2]})`;
}

How it works

The color function takes in two parameters, min and max, which determine the range from which the randomly generated color will be selected. To generate a random color, an array c is created with two of the values being the min and max numbers, and the third value being a random number within that range. This array is then used to create an RGB string using a template string. In this way, you can easily create a random color that fits within a specified range.

How to get the min and max

Matching the min and max values to a specific color is straightforward. Simply use the lowest and highest values of the color's RGB values as the min and max values, respectively. This ensures that the randomly generated color will be within the same color range as the target color.

Demo

MIN: 54 MAX: 177

R G B

Back

Comments


Be the first to comment!

Read More

Hero Image
Hero Image

Using Canvas in Node JS

Have you ever wanted to generate dynamic images on the server side? With Node Canvas, it's easy! Node Canvas is a module that allows ...

Why using eval in JS can be dangerous

It can cause malicious code to be executed with the same permissions as the webpage or extension, as well as it is slower than other alternatives due to the additional steps required for invoking the JavaScript interpreter. Minifiers al...

Warp Terminal screen shot
Warp Terminal screen shot

Warp Terminal

Warp terminal claims to be a "a blazingly fast, rust-based terminal reimagined from the ground up to work like...

Dynamically loading Google Fonts

Google Fonts is a great tool for web developers, it allows you to load in almost any font on to you website and use it with only a few lines of cod...