How to generate random pastel (or brighter) color in Javascript?

前端 未结 4 1079
迷失自我
迷失自我 2021-01-01 16:18

I am building a simple website that gives a random quote when I click a button, and with that, the background color changes. The thing is that sometimes the background color

4条回答
  •  有刺的猬
    2021-01-01 16:50

    You could choose among lighter colours by appropriately setting the background-color property using rgb.
    rgb(0,0,0) is black, while rgb(255,255,255) is white. You could therefore use random values which are closer to (but not higher than) 255.
    An example (using JQuery):

     var rand = Math.floor(Math.random() * 10);
     var colorQ = "rgb(" + (215 - rand * 3) + "," + (185 - rand * 5) + "," + (185 - rand * 10) + " )"; 
     $("body").css("background-color", colorQ);
    

    You can play around with the values until you find the colours that you prefer - keep in mind that the closer the 3 rgb values are to each other, the closer your colour will be to grey. E.g. rgb(100,100,100), rgb(221,221,221) and rgb(133,133,133) are all shades of grey. What changes is how light your grey will be.

提交回复
热议问题