How to generate random pastel (or brighter) color in Javascript?
HSL Colors
Using HSL Colors colors may be the easiest. HSL color values are specified in CSS as
hsl( hue, saturation%, lightness%)
where hue
is in range 0-360 (without a unit marker when using degrees), and both saturation
and lightness
are percentages with a trailing %
sign.
Note
"Bright" colors refer to the colors of an RGB color wheel formed by starting at red and then blending pure red into green, pure green into blue, and finally pure blue back into red again.
In HSL color space, bright colors are represented by a hue based on their position on the color wheel with
100%
saturation and a lightness value of50%
:hue
0
▶ ◀ hue360
saturation:100%
lightness:50%
Colors blend with white - and become more "pastel" as lightness increases above
50%
. A lightness value of100%
creates white regardless of what the values of hue and saturation are.Colors blend with grey as the saturation decreases and become more washed out depending on how low the saturation gets. A saturation value of
0%
creates a grey-scale tone based on lightness alone.Colors blend with black as lightness decreases below
50%
. A lightness value of0%
creates black no matter what the hue and saturation values are.
Warning
The human eye is least sensitive to the color blue. Black text on a blue background - or blue over black - is harder to read in comparison to other colors. If this becomes an issue for random color selection, example 2 shows one way to compensate.Example 1: Some random pastel colors with saturation in range 25-95%
and lightness in range 85-95%
:
function getColor(){
return "hsl(" + 360 * Math.random() + ',' +
(25 + 70 * Math.random()) + '%,' +
(85 + 10 * Math.random()) + '%)'
}
// Generate 20 colors
for( var i = 20; i--; ){
var item = document.createElement('div')
item.style.cssText = `
display:inline-block;
padding: 2em;
margin:5px;
border-radius:50%;
background: ${getColor()};
`
document.body.appendChild(item);
}
Javascript - Generate Random Pastel HEX/RGBA Color
To generate a range of color with pastel ton like, you can generate each canal with minimal value of 127:
generatePastelColor = () => {
let R = Math.floor((Math.random() * 127) + 127);
let G = Math.floor((Math.random() * 127) + 127);
let B = Math.floor((Math.random() * 127) + 127);
let rgb = (R << 16) + (G << 8) + B;
return `#${rgb.toString(16)}`;
}
document.querySelectorAll('#palette div').forEach( elem => {
elem.style.backgroundColor = generatePastelColor();
});
#palette {
width: 100px;
height: 100px;
}
#palette > div {
width: 100%;
height: 20px;
}
<div id="palette">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Javascript: generate random nice saturated colors (selected palette)
For fully saturated colours use the HSL colour space with H from 0-360, S at (or slightly below) 100% and L at 50%.
If you know the browser has CSS3 support you may be able to use that directly. Failing that, use an HSL to RGB algorithm (20ish lines of code) readily available via Google to convert into hex format.
The formulae for conversion from HSL to RGB are also on the Wikipedia page on HSL and are easily translated into Javascript (and most other languages too!)
Generate Random Color distinguishable to Humans
You could use a fixed set of colors, such as the ones listed in the jquery.color.js plugin.
List of colors from jquery.color.js plugin:
Colors = {};
Colors.names = {
aqua: "#00ffff",
azure: "#f0ffff",
beige: "#f5f5dc",
black: "#000000",
blue: "#0000ff",
brown: "#a52a2a",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgrey: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkviolet: "#9400d3",
fuchsia: "#ff00ff",
gold: "#ffd700",
green: "#008000",
indigo: "#4b0082",
khaki: "#f0e68c",
lightblue: "#add8e6",
lightcyan: "#e0ffff",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightyellow: "#ffffe0",
lime: "#00ff00",
magenta: "#ff00ff",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
orange: "#ffa500",
pink: "#ffc0cb",
purple: "#800080",
violet: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
white: "#ffffff",
yellow: "#ffff00"
};
The rest is simply picking a random property from a Javascript object.
Colors.random = function() {
var result;
var count = 0;
for (var prop in this.names)
if (Math.random() < 1/++count)
result = prop;
return result;
};
Using Colors.random()
might get you a human-readable color. I even powered an example below.
(function(){ Colors = {}; Colors.names = { aqua: "#00ffff", azure: "#f0ffff", beige: "#f5f5dc", black: "#000000", blue: "#0000ff", brown: "#a52a2a", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkviolet: "#9400d3", fuchsia: "#ff00ff", gold: "#ffd700", green: "#008000", indigo: "#4b0082", khaki: "#f0e68c", lightblue: "#add8e6", lightcyan: "#e0ffff", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightyellow: "#ffffe0", lime: "#00ff00", magenta: "#ff00ff", maroon: "#800000", navy: "#000080", olive: "#808000", orange: "#ffa500", pink: "#ffc0cb", purple: "#800080", violet: "#800080", red: "#ff0000", silver: "#c0c0c0", white: "#ffffff", yellow: "#ffff00" }; Colors.random = function() { var result; var count = 0; for (var prop in this.names) if (Math.random() < 1/++count) result = prop; return { name: result, rgb: this.names[result]}; }; var $placeholder = $(".placeholder"); $placeholder.click(function(){ var color = Colors.random(); $placeholder.css({'background-color': color.rgb}); $("#color").html("It's " + color.name); });})();
.placeholder { width: 150px; height: 150px; border: 1px solid black;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="placeholder"></div><span id="color">Click the square above.</span>
Get only light colors randomly using JavaScript
you can do so by cutting the string off forcing the random to be high number in HEX
function getRandomColor() {
var letters = 'BCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
quick dirty way
how to generate light and pastel colors randomly in android?
I don't understand why you add different numbers to each channel. Currently the result would be that you generate primarily red colors.
Also if you put a leading 0
in front of a number it is interpreted as an octal number. In other words it is interpreted as base 8.
So 010
would actually be an octal number and the decimal equivalent is counter intuitively 8
. The same goes for 001
, but in that case the octal number is the same as the decimal one. 1
in octal is equivalent to 1
in decimal.
Additionally you don't use a seed for your Random
instance. This is pretty bad because it means that you will always generate the exactly same colors. You need to use a seed from a sufficiently random source like System.currentTimeMillis()
.
But let's get to the point:
You can generate random pastel colors by randomly picking values for each channel and then mixing it with either white or with another pastel color. Try something like this:
final Random mRandom = new Random(System.currentTimeMillis());
public int generateRandomColor() {
// This is the base color which will be mixed with the generated one
final int baseColor = Color.WHITE;
final int baseRed = Color.red(baseColor);
final int baseGreen = Color.green(baseColor);
final int baseBlue = Color.blue(baseColor);
final int red = (baseRed + mRandom.nextInt(256)) / 2;
final int green = (baseGreen + mRandom.nextInt(256)) / 2;
final int blue = (baseBlue + mRandom.nextInt(256)) / 2;
return Color.rgb(red, green, blue);
}
You can pick a light grey as base color, or some other pastel color you like. You should probably not pick white as base color since then the generated colors tend to be to light for white text to be easily visible. Try slightly darker shades or for the best result some pastel color you like.
Random color generator
Use getRandomColor()
in place of "#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>
Generating pastel colors
Try this:
start_color = 128 # minimal color amount
total_offset = 64 # sum of individual color offsets above the minimal amount
'#' +
[0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b|
"%02x" % (start_color+b-a)
}.join
Actually, here's tiny Sinatra app that you can play with and see the results instantly:
require 'sinatra'
def get_pastel start_color, total_offset
'#' +
[0, rand(total_offset), rand(total_offset), total_offset].sort.each_cons(2).map{|a,b|
"%02x" % (start_color+b-a)
}.join
end
get '/:start_color/:total_offset' do |start_color, total_offset|
(0..20).map{c = get_pastel(start_color.to_i, total_offset.to_i)
"<span style='background-color:#{c}'>#{c}</span>\n"
}.join
end
Then fire up the browser and see how it looks:
http://localhost:4567/192/64
http://localhost:4567/128/128
;)
Related Topics
Implementing Flipcard on Click Instead of on Hover
Detect Browser Zoom Level Using JavaScript
JavaScript Hide/Show Div on Checkbox: Checked/Unchecked
How to Make a Rotated Element Height:100% of Its Parent
Toggle Sidebar Div with Another Div Using CSS/Javascript
How to Create a Table-Like CSS Layout with Divs
Show a Bootstrap Modal If Option Is Selected
Wrapping Text Inside Irregular Shapes
How to Get CSS Class by Name from Stylesheet
Fixed/Absolute Positioning Neglected in iOS When Focusing on Input
How to Add Alpha Filter to Any HTML Element and Keep the Other Filters in Ie
How to Get the Number of Children Div in CSS or SASS
Position Fixed - Horizontal Scroll
Jquery Draggable Event Changing the CSS of Child Element