loading...

How to Get Random Colors

azettl profile image Andreas Originally published at convertingcolors.com ・2 min read

For a random RGB color, we would need three numbers between 0 - 255, and for a color, in the HSL format, we need one number between 0 - 360 and two numbers between 0 - 100.

If we want a random HEX color, we would need a number between 0 - 16777215, which we then convert from decimal to hexadecimal.

RGB

The PHP code for a random RGB color would look like this:

<?php
  echo 'rgb(' . rand(0, 255) . ', ' . rand(0, 255) . ', ' . rand(0, 255) . ');';

In Javascript, the Math.random returns a number between 0 - 1, so we need to multiply this number by 255 to get random numbers between 0 - 255.

<script>
    alert('rgb(' + Math.floor((Math.random() * 255)) + ', ' + Math.floor((Math.random() * 255)) + ', ' + Math.floor((Math.random() * 255)) + ');');
</script>

HSL

In PHP we can get a random HSL color just like this:

<?php 
  echo 'hsl(' . rand(0, 360) . ', ' . rand(0, 100) . '%, ' . rand(0, 100) . '%);';

In Javascript, we need to multiply the return value from Math.random again this time with 360 for the first number and 100 for the following numbers.

<script>
    alert('hsl(' + Math.floor((Math.random() * 360)) + ', ' + Math.floor((Math.random() * 100)) + '%, ' + Math.floor((Math.random() * 100)) + '%);');
</script>

HEX

To get a random HEX color in PHP, we first create a random number between 0 - 16777215 (0xFFFFFF) with mt_rand, and then we convert this decimal number in a hexadecimal one.

As a HEX color always needs 3 or 6 digits, we will need to pad the string to a six-digit hex value with str_pad.

<?php
  echo '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);

For a better overview I split up the Javascript code in multiple lines:

<script>
    var randomNumber = Math.floor((Math.random() * 16777215));
    var randomHex    = randomNumber.toString(16);
    var randomHexColor = randomHex.padStart(6, 0);
    alert('#' + randomHexColor);
</script>

Discussion

markdown guide