Random Color Code Examples
Hex, RGB and HSL colors in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Every example below produces the same three things: a hex string such as #3FA7D6, an RGB triple and an HSL value, plus a small palette function. The guide first explains the color space the code draws from, then each language section shows the code and what is specific to that language.
Prefer no code? The interactive Colors generator does the same in the browser.
What a random color actually is
A screen color in CSS, image files and most UI toolkits is 24-bit sRGB: three channels (red, green, blue), each an integer from 0 to 255. That gives 256 × 256 × 256 = 16,777,216 colors. A hex code is the same number written in base 16: #RRGGBB, two hex digits per channel, so drawing one integer from 0 to 16,777,215 (0xFFFFFF) and formatting it as six hex digits is equivalent to drawing three channels separately.
HSL describes the same colors differently: hue is an angle on the color wheel (0–360°), saturation and lightness are percentages. It is not a different set of colors, only a different way to address them, and that makes it the better tool when you want control. Fix lightness at 80% and you only get pastels; fix saturation at 0% and you get greys.
Uniform colors versus useful colors
Drawing uniformly over all 16.7 million values gives every color the same chance, which is what tests and fuzzing want. It is rarely what a person wants to look at: many uniform picks are muddy browns and dark olives, and two picks in a row often look nearly the same. For charts, tags and avatars, draw in HSL instead and constrain it:
- Pastel: any hue, saturation 25–95%, lightness 70–90%.
- Readable on white: keep lightness below about 45% so text in that color passes a 4.5:1 contrast ratio more often (still check it).
- Distinct palette: instead of independent random hues, start from one random hue and add the golden angle (about 137.5°) for each next color. Neighbours then never land close together on the wheel, however many colors you need.
Secure or non-secure random?
Colors almost never need a cryptographically secure generator. Nobody gains anything by predicting the next chart color, so the fast default generator of each language (Math.random(), random, java.util.Random, mt19937…) is the right choice. Use the secure source (crypto.getRandomValues(), secrets, SecureRandom, random_int()) only when the color is derived from something that must stay unguessable, such as a visual fingerprint of a key.
The opposite need is more common: reproducible colors. Seed the generator with a fixed value (or hash the user ID or category name into the seed) and the same input always gets the same color across page loads and servers, which keeps a dashboard legend stable.
Common mistakes
- Off-by-one at the top of the range. Most integer functions exclude their upper bound, so
nextInt(0xFFFFFF)can never produce white (#FFFFFF). Draw below0x1000000instead. Functions that include both ends (Python'srandint, PHP'smt_rand) take0xFFFFFF. - Missing zero padding. The number 4,095 is
FFFin hex, which CSS reads as the short form#FFF(white) instead of#000FFF(blue). Always pad to six digits, and each channel to two. - Scaling floats badly.
Math.floor(Math.random() * 255)never returns 255; multiply by 256. - Different channel ranges per library. Matplotlib and some shader APIs expect floats from 0.0 to 1.0, CSS and most toolkits integers from 0 to 255, and HSL in CSS needs the % signs.
- Trusting random colors for accessibility. A random text or background color fails WCAG contrast a large part of the time. Compute the contrast ratio, or generate only in a lightness band that suits your background.
Common Use Cases
- Series colors for charts and dashboards (Chart.js, D3, matplotlib, JFreeChart)
- Background colors for initials avatars and user or category tags
- Placeholder palettes for design mockups and theme prototyping
- Test data for color pickers, CSS parsers and image pipelines
- Generative art, game objects and procedural textures
Random Color Code Examples in PHP
Learn how to generate random colors in PHP using hex (#RRGGBB), RGB (red, green, blue), and HSL (hue, saturation, lightness) formats for web development and design.
<?php
// Generate Random Hex Color
function randomHexColor() {
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
echo "Hex Color: " . randomHexColor() . "\n";
// Generate Random RGB Color
function randomRgbColor() {
$r = mt_rand(0, 255);
$g = mt_rand(0, 255);
$b = mt_rand(0, 255);
return "rgb($r, $g, $b)";
}
echo "RGB Color: " . randomRgbColor() . "\n";
// Generate Random HSL Color
function randomHslColor() {
$h = mt_rand(0, 360); // Hue: 0-360 degrees
$s = mt_rand(0, 100); // Saturation: 0-100%
$l = mt_rand(0, 100); // Lightness: 0-100%
return "hsl($h, $s%, $l%)";
}
echo "HSL Color: " . randomHslColor() . "\n";
// Generate Pastel Color (high lightness)
function randomPastelColor() {
$h = mt_rand(0, 360);
$s = mt_rand(25, 100);
$l = mt_rand(70, 90); // High lightness for pastel
return "hsl($h, $s%, $l%)";
}
echo "Pastel Color: " . randomPastelColor() . "\n";
// Convert RGB to Hex
function rgbToHex($r, $g, $b) {
return sprintf("#%02X%02X%02X", $r, $g, $b);
}
$r = mt_rand(0, 255);
$g = mt_rand(0, 255);
$b = mt_rand(0, 255);
echo "RGB ($r, $g, $b) -> Hex: " . rgbToHex($r, $g, $b);
How it works in PHP
PHP provides mt_rand() for generating random integers. For hex colors, generate a random number between 0 and 16777215 (0xFFFFFF) and format with sprintf('#%06X') to create a 6-digit hex code. RGB colors use three values (0-255) for red, green, and blue channels. HSL uses hue (0-360°), saturation (0-100%), and lightness (0-100%). For pastel colors, use high lightness values (70-90%). The %02X format ensures each color component is represented with exactly 2 hex digits, padding with zeros if necessary.
Sample output
Hex Color: #3FA7D6 RGB Color: rgb(142, 68, 173) HSL Color: hsl(287, 43%, 67%) Pastel Color: hsl(156, 78%, 82%) RGB (255, 99, 71) -> Hex: #FF6347
PHP notes
- Since PHP 7.1
rand()is an alias ofmt_rand(); userandom_int()when the value must be unpredictable. mt_rand(0, 0xFFFFFF)includes both bounds, so white is reachable.sprintf('#%06X', $n)pads to six digits;%02Xpads one channel.
Random Color Code Examples in JavaScript
Generate random colors in JavaScript using hex, RGB, and HSL formats for web applications, canvas drawing, and dynamic UI elements.
// Generate Random Hex Color
function randomHexColor() {
return '#' + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0');
}
console.log('Hex Color:', randomHexColor());
// Generate Random RGB Color
function randomRgbColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
console.log('RGB Color:', randomRgbColor());
// Generate Random HSL Color
function randomHslColor() {
const h = Math.floor(Math.random() * 361); // 0-360
const s = Math.floor(Math.random() * 101); // 0-100
const l = Math.floor(Math.random() * 101); // 0-100
return `hsl(${h}, ${s}%, ${l}%)`;
}
console.log('HSL Color:', randomHslColor());
// Generate Pastel Color
function randomPastelColor() {
const h = Math.floor(Math.random() * 361);
const s = Math.floor(Math.random() * 76) + 25; // 25-100
const l = Math.floor(Math.random() * 21) + 70; // 70-90
return `hsl(${h}, ${s}%, ${l}%)`;
}
console.log('Pastel Color:', randomPastelColor());
// Generate Array of Random Colors
function generateColorPalette(count) {
return Array.from({ length: count }, () => randomHexColor());
}
console.log('Color Palette:', generateColorPalette(5));
// RGB to Hex Conversion
function rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
}
console.log('RGB to Hex:', rgbToHex(255, 99, 71));
How it works in JavaScript
JavaScript generates random colors using Math.random(). For hex colors, generate a random number below 16777216 (0x1000000), convert to base-16 with toString(16), and pad to 6 digits. RGB uses Math.floor(Math.random() * 256) for each channel (0-255). HSL uses hue (0-360), saturation (0-100%), and lightness (0-100%). The padStart() method ensures proper formatting with leading zeros. For pastel colors, restrict lightness to 70-90% range for softer tones.
Sample output
Hex Color: #7b3f9e RGB Color: rgb(189, 78, 42) HSL Color: hsl(204, 67%, 53%) Pastel Color: hsl(89, 56%, 81%) Color Palette: [ '#2a9d8f', '#e76f51', '#f4a261', '#e9c46a', '#264653' ] RGB to Hex: #ff6347
JavaScript notes
Math.random()is not cryptographically secure;crypto.getRandomValues(new Uint8Array(3))gives three secure channel bytes.toString(16).padStart(6, '0')keeps short numbers from turning into 3-digit CSS shorthand.Array.from({ length: n }, randomHex)builds a palette in one expression.
Random Color Code Examples in Python
Generate random colors in Python using hex, RGB, and HSL formats for data visualization, matplotlib plots, and web applications.
import random
# Generate Random Hex Color
def random_hex_color():
return f"#{random.randint(0, 0xFFFFFF):06x}"
print(f"Hex Color: {random_hex_color()}")
# Generate Random RGB Color
def random_rgb_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return f"rgb({r}, {g}, {b})"
print(f"RGB Color: {random_rgb_color()}")
# Generate Random HSL Color
def random_hsl_color():
h = random.randint(0, 360)
s = random.randint(0, 100)
l = random.randint(0, 100)
return f"hsl({h}, {s}%, {l}%)"
print(f"HSL Color: {random_hsl_color()}")
# Generate Pastel Color
def random_pastel_color():
h = random.randint(0, 360)
s = random.randint(25, 100)
l = random.randint(70, 90)
return f"hsl({h}, {s}%, {l}%)"
print(f"Pastel Color: {random_pastel_color()}")
# Generate Color Palette (list of hex colors)
def generate_color_palette(count):
return [random_hex_color() for _ in range(count)]
print(f"Color Palette: {generate_color_palette(5)}")
# RGB Tuple for Matplotlib
def random_rgb_tuple():
return (random.random(), random.random(), random.random())
print(f"Matplotlib RGB: {random_rgb_tuple()}")
# RGB to Hex Conversion
def rgb_to_hex(r, g, b):
return f"#{r:02x}{g:02x}{b:02x}"
print(f"RGB to Hex: {rgb_to_hex(255, 99, 71)}")
How it works in Python
Python's random module generates random integers with randint(). For hex colors, use :06x format specifier to create a 6-digit hexadecimal string. RGB colors use three random integers (0-255) for each channel. HSL uses hue (0-360°), saturation (0-100%), and lightness (0-100%). For matplotlib compatibility, use random.random() to generate RGB tuples with values 0.0-1.0. The :02x format ensures 2-digit hex values with leading zeros.
Sample output
Hex Color: #4a7c59 RGB Color: rgb(207, 142, 89) HSL Color: hsl(318, 72%, 45%) Pastel Color: hsl(203, 67%, 84%) Color Palette: ['#2d5a8f', '#e85d75', '#ffa600', '#58b368', '#bc5090'] Matplotlib RGB: (0.7328428975265018, 0.2891647358533935, 0.9204859842875636) RGB to Hex: #ff6347
Python notes
random.randint(a, b)includes both endpoints.- Matplotlib expects RGB tuples of floats from 0.0 to 1.0, which
random.random()gives directly. random.seed(42)makes a palette reproducible; usesecrets.token_hex(3)for an unpredictable hex color.
Random Color Code Examples in Java
Generate random colors in Java using hex strings, RGB values, and java.awt.Color objects for Swing, JavaFX, and Android applications.
import java.awt.Color;
import java.util.Random;
public class RandomColorGenerator {
private static final Random random = new Random();
public static void main(String[] args) {
// Generate Random Hex Color
String hexColor = randomHexColor();
System.out.println("Hex Color: " + hexColor);
// Generate Random RGB Color String
String rgbColor = randomRgbColor();
System.out.println("RGB Color: " + rgbColor);
// Generate Random java.awt.Color Object
Color awtColor = randomColor();
System.out.println("AWT Color: " + colorToRgbString(awtColor));
// Generate Random HSL Color
String hslColor = randomHslColor();
System.out.println("HSL Color: " + hslColor);
// Generate Pastel Color
String pastelColor = randomPastelColor();
System.out.println("Pastel Color: " + pastelColor);
}
public static String randomHexColor() {
int rgb = random.nextInt(0x1000000);
return String.format("#%06X", rgb);
}
public static String randomRgbColor() {
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return String.format("rgb(%d, %d, %d)", r, g, b);
}
public static Color randomColor() {
return new Color(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256)
);
}
public static String randomHslColor() {
int h = random.nextInt(361);
int s = random.nextInt(101);
int l = random.nextInt(101);
return String.format("hsl(%d, %d%%, %d%%)", h, s, l);
}
public static String randomPastelColor() {
int h = random.nextInt(361);
int s = 25 + random.nextInt(76);
int l = 70 + random.nextInt(21);
return String.format("hsl(%d, %d%%, %d%%)", h, s, l);
}
public static String colorToRgbString(Color color) {
return String.format("rgb(%d, %d, %d)",
color.getRed(), color.getGreen(), color.getBlue());
}
}
How it works in Java
Java uses java.util.Random for generating random values. For hex colors, use random.nextInt(0x1000000) to generate values 0-16777215 and format with String.format("#%06X"). The java.awt.Color class accepts RGB values (0-255) in its constructor. HSL colors are formatted as strings since Java doesn't have built-in HSL support. Use random.nextInt(256) for RGB channels (0-255 inclusive). For Swing/JavaFX applications, Color objects integrate directly with UI components.
Sample output
Hex Color: #5B9AA0 RGB Color: rgb(167, 94, 201) AWT Color: rgb(89, 142, 63) HSL Color: hsl(287, 59%, 48%) Pastel Color: hsl(156, 72%, 83%)
Java notes
random.nextInt(n)excludesn: usenextInt(0x1000000)andnextInt(256).- Prefer
ThreadLocalRandom.current()when several threads generate colors. - JavaFX uses
javafx.scene.paint.Color(doubles 0–1), Swing and AWT usejava.awt.Color(ints 0–255).
Random Color Code Examples in C#
Generate random colors in C# using hex strings, RGB values, and System.Drawing.Color objects for WPF, WinForms, and ASP.NET applications.
using System;
using System.Drawing;
class RandomColorGenerator
{
private static readonly Random random = new Random();
static void Main()
{
// Generate Random Hex Color
string hexColor = RandomHexColor();
Console.WriteLine($"Hex Color: {hexColor}");
// Generate Random RGB Color String
string rgbColor = RandomRgbColor();
Console.WriteLine($"RGB Color: {rgbColor}");
// Generate Random System.Drawing.Color
Color color = RandomColor();
Console.WriteLine($"Color Object: {ColorToRgbString(color)}");
// Generate Random HSL Color
string hslColor = RandomHslColor();
Console.WriteLine($"HSL Color: {hslColor}");
// Generate Pastel Color
string pastelColor = RandomPastelColor();
Console.WriteLine($"Pastel Color: {pastelColor}");
}
public static string RandomHexColor()
{
int rgb = random.Next(0x1000000);
return $"#{rgb:X6}";
}
public static string RandomRgbColor()
{
int r = random.Next(256);
int g = random.Next(256);
int b = random.Next(256);
return $"rgb({r}, {g}, {b})";
}
public static Color RandomColor()
{
return Color.FromArgb(
random.Next(256),
random.Next(256),
random.Next(256)
);
}
public static string RandomHslColor()
{
int h = random.Next(361);
int s = random.Next(101);
int l = random.Next(101);
return $"hsl({h}, {s}%, {l}%)";
}
public static string RandomPastelColor()
{
int h = random.Next(361);
int s = random.Next(25, 101);
int l = random.Next(70, 91);
return $"hsl({h}, {s}%, {l}%)";
}
public static string ColorToRgbString(Color color)
{
return $"rgb({color.R}, {color.G}, {color.B})";
}
}
How it works in C#
C# uses System.Random for generating random values. For hex colors, use random.Next(0x1000000) to generate values 0-16777215 and format with :X6 to create 6-digit hex. The System.Drawing.Color struct is created with Color.FromArgb() accepting RGB values (0-255). HSL colors are formatted as strings since C# doesn't have built-in HSL support. Use random.Next(256) for RGB channels (0-255 exclusive upper bound). String interpolation with $"" provides clean formatting.
Sample output
Hex Color: #7A3E9D RGB Color: rgb(198, 112, 67) Color Object: rgb(142, 201, 89) HSL Color: hsl(204, 78%, 56%) Pastel Color: hsl(312, 68%, 79%)
C# notes
random.Next(n)excludesn: useNext(0x1000000)andNext(256).- On .NET 6+,
Random.Sharedis thread-safe; a single sharednew Random()is not. - WPF uses
System.Windows.Media.Color;System.Drawing.Coloris for WinForms and GDI+.
Random Color Code Examples in C++
Generate random colors in C++ using hex strings, RGB values, and Qt QColor objects with modern C++11 random number generation.
#include <iostream>
#include <random>
#include <sstream>
#include <iomanip>
#include <string>
class RandomColorGenerator {
private:
std::random_device rd;
std::mt19937 gen;
std::uniform_int_distribution<> rgb_dist;
std::uniform_int_distribution<> hue_dist;
std::uniform_int_distribution<> percent_dist;
public:
RandomColorGenerator()
: gen(rd()),
rgb_dist(0, 255),
hue_dist(0, 360),
percent_dist(0, 100) {}
std::string randomHexColor() {
std::stringstream ss;
ss << "#"
<< std::hex << std::setfill('0')
<< std::setw(2) << rgb_dist(gen)
<< std::setw(2) << rgb_dist(gen)
<< std::setw(2) << rgb_dist(gen);
return ss.str();
}
std::string randomRgbColor() {
int r = rgb_dist(gen);
int g = rgb_dist(gen);
int b = rgb_dist(gen);
return "rgb(" + std::to_string(r) + ", " +
std::to_string(g) + ", " +
std::to_string(b) + ")";
}
std::string randomHslColor() {
int h = hue_dist(gen);
int s = percent_dist(gen);
int l = percent_dist(gen);
return "hsl(" + std::to_string(h) + ", " +
std::to_string(s) + "%, " +
std::to_string(l) + "%)";
}
std::string randomPastelColor() {
int h = hue_dist(gen);
std::uniform_int_distribution<> pastel_s(25, 100);
std::uniform_int_distribution<> pastel_l(70, 90);
int s = pastel_s(gen);
int l = pastel_l(gen);
return "hsl(" + std::to_string(h) + ", " +
std::to_string(s) + "%, " +
std::to_string(l) + "%)";
}
struct RGB {
int r, g, b;
};
RGB randomRgbStruct() {
return {rgb_dist(gen), rgb_dist(gen), rgb_dist(gen)};
}
};
int main() {
RandomColorGenerator colorGen;
std::cout << "Hex Color: " << colorGen.randomHexColor() << std::endl;
std::cout << "RGB Color: " << colorGen.randomRgbColor() << std::endl;
std::cout << "HSL Color: " << colorGen.randomHslColor() << std::endl;
std::cout << "Pastel: " << colorGen.randomPastelColor() << std::endl;
auto rgb = colorGen.randomRgbStruct();
std::cout << "RGB Struct: (" << rgb.r << ", "
<< rgb.g << ", " << rgb.b << ")" << std::endl;
return 0;
}
How it works in C++
Modern C++ (C++11+) uses std::random_device for seed generation and std::mt19937 (Mersenne Twister) for high-quality random numbers. std::uniform_int_distribution generates uniformly distributed integers. For hex colors, use std::stringstream with std::hex and std::setw(2) for 2-digit hex values. RGB uses three random integers (0-255). Create member distributions in the class for efficiency instead of recreating them. For Qt applications, you can create QColor objects with RGB values.
Sample output
Hex Color: #6b4e9a RGB Color: rgb(187, 98, 143) HSL Color: hsl(234, 67%, 54%) Pastel: hsl(89, 78%, 85%) RGB Struct: (142, 207, 89)
C++ notes
- Prefer
std::mt19937withstd::uniform_int_distributionoverrand() % 256, which is biased and low quality. - Seed once from
std::random_deviceand reuse the engine and distributions. std::setw(2) << std::setfill('0') << std::hexpads each channel to two digits.
Random Color Code Examples in Ruby
Generate random colors in Ruby using hex, RGB, and HSL formats for Rails applications, web development, and data visualization.
# Generate Random Hex Color
def random_hex_color
"#%06x" % rand(0x1000000)
end
puts "Hex Color: #{random_hex_color}"
# Generate Random RGB Color
def random_rgb_color
r = rand(256)
g = rand(256)
b = rand(256)
"rgb(#{r}, #{g}, #{b})"
end
puts "RGB Color: #{random_rgb_color}"
# Generate Random HSL Color
def random_hsl_color
h = rand(361)
s = rand(101)
l = rand(101)
"hsl(#{h}, #{s}%, #{l}%)"
end
puts "HSL Color: #{random_hsl_color}"
# Generate Pastel Color
def random_pastel_color
h = rand(361)
s = rand(25..100)
l = rand(70..90)
"hsl(#{h}, #{s}%, #{l}%)"
end
puts "Pastel Color: #{random_pastel_color}"
# Generate Color Palette (Array of hex colors)
def generate_color_palette(count)
count.times.map { random_hex_color }
end
puts "Color Palette: #{generate_color_palette(5).inspect}"
# RGB to Hex Conversion
def rgb_to_hex(r, g, b)
"#%02x%02x%02x" % [r, g, b]
end
puts "RGB to Hex: #{rgb_to_hex(255, 99, 71)}"
# Generate with SecureRandom (for cryptographic security)
require 'securerandom'
def secure_random_hex_color
"#" + SecureRandom.hex(3)
end
puts "Secure Hex: #{secure_random_hex_color}"
How it works in Ruby
Ruby's rand() generates random numbers. For hex colors, use rand(0x1000000) to generate 0-16777215 and format with "%06x" for 6-digit hex. RGB colors use rand(256) for each channel (0-255). HSL uses hue (0-360), saturation (0-100%), and lightness (0-100%). Ruby's range syntax rand(25..100) is inclusive. Use times.map for generating arrays of colors. SecureRandom.hex(3) generates 6 random hex characters (3 bytes) for cryptographically secure colors.
Sample output
Hex Color: #8a5c9e RGB Color: rgb(167, 89, 201) HSL Color: hsl(287, 68%, 59%) Pastel Color: hsl(156, 72%, 84%) Color Palette: ["#3d7ea6", "#e85d75", "#ffa600", "#58b368", "#bc5090"] RGB to Hex: #ff6347 Secure Hex: #7b3f9e
Ruby notes
rand(n)returns 0 to n−1, whilerand(a..b)includesb.SecureRandom.hex(3)gives six secure hex digits in one call.Array.new(n) { random_hex }orn.times.mapbuilds a palette.
Random Color Code Examples in Go
Generate random colors in Go using hex strings, RGB values, and color.RGBA objects with math/rand package for web and graphics applications.
package main
import (
"fmt"
"image/color"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
// Generate Random Hex Color
fmt.Println("Hex Color:", randomHexColor())
// Generate Random RGB Color
fmt.Println("RGB Color:", randomRgbColor())
// Generate Random color.RGBA
rgba := randomColorRGBA()
fmt.Printf("RGBA: color.RGBA{R:%d, G:%d, B:%d, A:255}\n",
rgba.R, rgba.G, rgba.B)
// Generate Random HSL Color
fmt.Println("HSL Color:", randomHslColor())
// Generate Pastel Color
fmt.Println("Pastel Color:", randomPastelColor())
// Generate Color Palette
palette := generateColorPalette(5)
fmt.Println("Color Palette:", palette)
}
func randomHexColor() string {
return fmt.Sprintf("#%06x", rand.Intn(0x1000000))
}
func randomRgbColor() string {
r := rand.Intn(256)
g := rand.Intn(256)
b := rand.Intn(256)
return fmt.Sprintf("rgb(%d, %d, %d)", r, g, b)
}
func randomColorRGBA() color.RGBA {
return color.RGBA{
R: uint8(rand.Intn(256)),
G: uint8(rand.Intn(256)),
B: uint8(rand.Intn(256)),
A: 255,
}
}
func randomHslColor() string {
h := rand.Intn(361)
s := rand.Intn(101)
l := rand.Intn(101)
return fmt.Sprintf("hsl(%d, %d%%, %d%%)", h, s, l)
}
func randomPastelColor() string {
h := rand.Intn(361)
s := rand.Intn(76) + 25 // 25-100
l := rand.Intn(21) + 70 // 70-90
return fmt.Sprintf("hsl(%d, %d%%, %d%%)", h, s, l)
}
func generateColorPalette(count int) []string {
palette := make([]string, count)
for i := 0; i < count; i++ {
palette[i] = randomHexColor()
}
return palette
}
func rgbToHex(r, g, b uint8) string {
return fmt.Sprintf("#%02x%02x%02x", r, g, b)
}
How it works in Go
Go's math/rand package draws the values: rand.Intn(0x1000000) for a hex color formatted with fmt.Sprintf("#%06x", n), rand.Intn(256) for each RGB channel, and color.RGBA from image/color stores channels as uint8. HSL has no standard type, so the example formats it as a CSS string. make([]string, count) preallocates the palette slice.
Sample output
Hex Color: #7b3f9e
RGB Color: rgb(189, 78, 142)
RGBA: color.RGBA{R:207, G:142, B:89, A:255}
HSL Color: hsl(287, 67%, 54%)
Pastel Color: hsl(156, 78%, 82%)
Color Palette: [#2d5a8f #e85d75 #ffa600 #58b368 #bc5090]
Go notes
- Since Go 1.20 the global
math/randsource is seeded automatically andrand.Seedis deprecated: on current Go, drop that line. rand.Intn(n)excludesn;math/rand/v2offersrand.IntNwith the same contract.- Use
crypto/randwhen the color must be unpredictable.
Try the Interactive Generator
Need values right now rather than code? The Colors generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE COLORS GENERATOR →