Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random grey colors in javascript

I have a function and would like to generate only grey colors. How can I do this with the code below? I'm pretty new to javascript! I'd appreciate any help. I'm using Paper.js

 function onMouseDown(event) {
        path = new Path();
        path.fillColor = {
            hue: Math.random() * 360,
            //saturation: 0,
            //brightness: 0.5
        };

        path.add(event.point);
    }
like image 268
nattienatz Avatar asked Dec 22 '25 14:12

nattienatz


1 Answers

Since grey colours have equal RGB components you can generate a hex in the range 0 - ff and use it for each of the R,G,B parts:

function randomGreyHex() {
  var v = (Math.random()*(256)|0).toString(16);//bitwise OR. Gives value in the range 0-255 which is then converted to base 16 (hex).
  return "#" + v + v + v;
}

/* demo usage: */
var div = document.querySelector("div");
div.addEventListener("click", function() {
  var grey = randomGreyHex();
  this.style.backgroundColor = grey;
  this.innerHTML = grey;
});
div {
  height: 100px;
  border: 1px solid red;
  text-shadow: 0 0 10px white;
}
<div id="div">click me</div>
like image 185
Moob Avatar answered Dec 24 '25 03:12

Moob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!