5
In this question, teach how generate random colors through PHP.
How to do this in Javascript?
5
In this question, teach how generate random colors through PHP.
How to do this in Javascript?
6
In a row, you can do it like this:
'#' + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0');
Brief explanation of the above expression:
Math.floor
round the number down so as to remove the decimal part of the number generated by the function Math.random
.Number.prototype.toString(16)
converts the number into string in its hexadecimal representation.String.prototype.padStart(6, '0')
ensures that the hexadecimal string always has six digits.And a Javascript adaptation of this other answer:
let str = '#';
while (str.length < 7) {
str += Math.floor(Math.random() * 0x10).toString(16);
}
5
To title of curiosity it is also possible to use the Encryption API to generate random numbers.
Unlike other encryption API methods, the method RandomSource.getRandomValues()
allows to obtain random values independent of the security context in which the code is being executed.
RandomSource.getRandomValues()
accepted as a parameter an object typedArray
and fills it with random numbers and returns it.
The method Typedarray.prototype.reduce() apply a function to an accumulator and each array value to reduce them to a single value.
let rgb = window.crypto.getRandomValues(new Uint8Array(3))
.reduce((acc, val) => acc + val.toString(16), "#");
console.log(rgb)
Table of compatibility of RandomSource.getRandomValues()
Math.Random vs Crypto.getRandom
-2
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()">Gerar Cor</button>
Could add an explanation of what the code does?
Browser other questions tagged javascript colors
You are not signed in. Login or sign up in order to post.
Very cool, Augusto! + 1 :) But I’ll leave the same question I left on another answer: In view of the API
crypto
was made for purposes that require cryptographically secure numbers, is it really necessary to use something as powerful and therefore more computationally demanding for something as simple as generating a random color? I know you know the answer to that question, but I leave that to other people who may not know it.– Luiz Felipe