Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo màu ngẫu nhiên (Random Color Generator) trong JavaScript

Tạo mã màu hex ngẫu nhiên (ví dụ: #A3F2C1) và áp dụng cho element.

Logic:

  • Mã hex: # + 6 ký tự từ 0-9, A-F
  • Mỗi ký tự: chọn ngẫu nhiên từ 16 ký tự
  • Lặp 6 lần

Ví dụ minh họa (Vanilla JS - Không cần jQuery)

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Color Generator</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; text-align: center; }
    #colorBox { width: 150px; height: 150px; margin: 20px auto; border: 3px solid #333; border-radius: 12px; transition: background 0.3s; }
    #colorCode { font-family: monospace; font-size: 24px; font-weight: bold; margin: 10px 0; }
    button { padding: 12px 24px; font-size: 16px; cursor: pointer; background: #333; color: white; border: none; border-radius: 6px; }
    button:hover { background: #555; }
  </style>
</head>
<body>
  <h1>Random Color Generator</h1>
  <div id="colorBox" style="background-color: #FF0"></div>
  <div id="colorCode">#FF0</div>
  <button id="btn">Tạo màu ngẫu nhiên</button>
  
  <script>
    const colorBox = document.getElementById('colorBox');
    const colorCode = document.getElementById('colorCode');
    const btn = document.getElementById('btn');
    
    // Hàm tạo mã màu hex ngẫu nhiên
    function getRandomColor() {
      const hexChars = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += hexChars[Math.floor(Math.random() * 16)];
      }
      return color;
    }
    
    // Cách 2: Ngắn gọn hơn (ES6)
    // const getRandomColor = () => '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
    
    btn.addEventListener('click', () => {
      const color = getRandomColor();
      colorBox.style.backgroundColor = color;
      colorCode.textContent = color;
    });
    
    // Bonus: Auto change mỗi 2 giây
    // let autoInterval = setInterval(() => btn.click(), 2000);
    // btn.addEventListener('dblclick', () => clearInterval(autoInterval));
  </script>
</body>
</html>

Kết quả

Mặc định màu vàng (#FF0). Nhấn nút → Màu ngẫu nhiên (VD: #A3F2C1, #FF5733, #33FF57...).

Các cách tạo màu ngẫu nhiên khác:

// 1. RGB ngẫu nhiên
function randomRGB() {
  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})`;
}

// 2. HSL ngẫu nhiên (dễ tạo màu pastel, saturated...)
function randomHSL() {
  const h = Math.floor(Math.random() * 360);
  const s = Math.floor(Math.random() * 100) + '%';
  const l = Math.floor(Math.random() * 100) + '%';
  return `hsl(${h}, ${s}, ${l})`;
}

// 3. Từ mảng màu định sẵn (theme colors)
const palette = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'];
const randomFromPalette = () => palette[Math.floor(Math.random() * palette.length)];

// 4. Crypto-secure (cho security context)
function secureRandomColor() {
  const bytes = new Uint8Array(3);
  crypto.getRandomValues(bytes);
  return '#' + Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}

Ứng dụng:

  • Avatar placeholder (random background)
  • Chart/data visualization colors
  • Game development
  • UI theming, dark/light mode preview
  • Creative coding, generative art

Lưu ý:

  • Math.random() không cryptographically secure - không dùng cho security token
  • Dùng crypto.getRandomValues() cho security context
  • HSL cho phép kiểm soát saturation/lightness tốt hơn RGB/Hex