1 minute read

I’ve been working on a project using Phoenix LiveView, which serves up server-rendered HTML over websockets. I needed a way to generate a random RGB colour on the backend, so I wrote this function that seems to do the job.

def generate_random_colour do
  :rand.uniform(16_777_216)
  |> Kernel.-(1)
  |> Integer.to_string(16)
  |> String.pad_leading(6, "0")
  |> (fn s -> "##{s}" end).()
end

Let’s Break it down!

1. Generate a random number

  :rand.uniform(16_777_216)
  |> Kernel.-(1)

This erlang function generates a random number between 1 and 16,777,216, representing all possible colours in the standard RGB colour space. By subtracting 1, we include 0 in the range, which corresponds to the lowest CSS colour, #000000. The highest number, 16,777,215, gives us #FFFFFF.

2. Convert to Hexadecimal

  |> Integer.to_string(16)

It converts the random integer into a hexadecimal string, which is used by HTML and CSS for colours.

3. Pad with leading zeros

  |> String.pad_leading(6, "0")

This ensures the string is at least 6 characters and pads the string with leading zeros until it is. For example, suppose the random number generator produced the number 3. After subtracting one, and converting to hexadecimal - the string so far would be “2” and not “000002” - which is what we need for use with HTML and CSS.

4. Add a hash (#)

  |> (fn s -> "##{s}" end).()

Finally, this anonymous function prepends the random colour with a “#” which makes it usable in HTML and CSS.

Example output:

iex> MyModule.generate_random_colour()
"#A3F1C7"

I hope this is useful! For more fun, experiment with these variations:

  • Return the RGB values as a tuple: {63, 162, 188}.
  • Generate only light or dark colours.

Happy coding!