Web color can be expressed in hexadecimal , or as RGB value. With the RGB value, each color is represented as a number between 0 and 255. The example demonstrates one technique to generate a color, using one function to randomly generate the number, and a second to return RGB formatted string. Older browsers may not support the RGB notation. To use a hexadecimal notation, the randomColorfunction can be altered to hexadecimal
The hexadecimal notation is used (#ffffff), and the generated decimal number is converted to hexadecimal notation, using the Numberobjects toStringmethod. Since a decimal value of something like zero converts to a single-digit character and the format needs to be double-digit, the length is tested and modified accordingly. All the major browsers support both the RGB and hexadecimal notation, except IE7, which only supports hexadecimal.
function randomColor() {
return "rgb(" + randomVal(255) + "," + randomVal(255) + "," + randomVal(255) + ")";
}
function randomVal(val) {
return Math.floor(Math.random() * val);
}
check the example below :-
<p data-height="317" data-theme-id="0" data-slug-hash="MwmOGj" data-default-tab="result" data-user="Sunil_chatterji" class="codepen">See the Pen <a href="http://codepen.io/Sunil_chatterji/pen/MwmOGj/">Randomization of the colors </a> by sunil.chatterji (<a href="http://codepen.io/Sunil_chatterji">@Sunil_chatterji</a>) on <a href="http://codepen.io">CodePen</a>.</p>
Reference
Randomly Generating Colors - JavaScript Cookbook
0 Comment(s)