萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作 HSV/RGB/HEX 色彩選取器:滑鼠移動即時換算顏色值

在彩虹漸層色帶上移動滑鼠,即時顯示對應的 HSV、RGB、HEX 三種顏色格式數值。展示色彩空間轉換算法(HSV→RGB→HEX)與 DOM 事件綁定。

色彩空間轉換核心函式

// HSV (H:0-360, S:0-1, V:0-1) → RGB (0-255)
function hsvToRgb(h, s, v) {
  var i = Math.floor(h / 60);
  var f = h / 60 - i;
  var p = v * (1 - s);
  var q = v * (1 - f * s);
  var t = v * (1 - (1 - f) * s);
  var r, g, b;
  switch (i % 6) {
    case 0: r=v; g=t; b=p; break;
    case 1: r=q; g=v; b=p; break;
    case 2: r=p; g=v; b=t; break;
    case 3: r=p; g=q; b=v; break;
    case 4: r=t; g=p; b=v; break;
    case 5: r=v; g=p; b=q; break;
  }
  return [Math.round(r*255), Math.round(g*255), Math.round(b*255)];
}

// RGB → HEX
function rgbToHex(r, g, b) {
  return '#' + [r,g,b].map(function(v){ return v.toString(16).padStart(2,'0'); }).join('');
}

完整互動範例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HSV/RGB/HEX 色彩選取器</title>
<style>
  body { font-family:sans-serif; padding:20px; background:#f5f5f5; }
  .picker { display:flex; gap:20px; align-items:flex-start; max-width:900px; margin:0 auto; }
  .color-band { position:relative; width:360px; height:200px; border:1px solid #ccc; border-radius:4px; overflow:hidden; cursor:crosshair; background:linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); }
  .color-band::after { content:''; position:absolute; inset:0; background:linear-gradient(to bottom, rgba(255,255,255,0), rgba(0,0,0,1)); pointer-events:none; }
  .crosshair { position:absolute; width:20px; height:20px; border:2px solid #fff; border-radius:50%; box-shadow:0 0 0 2px #000; transform:translate(-50%,-50%); pointer-events:none; transition:transform 0.05s; }
  .values { display:grid; gap:12px; min-width:220px; }
  .value-box { background:#fff; border:1px solid #ddd; border-radius:6px; padding:16px; box-shadow:0 2px 8px rgba(0,0,0,0.05); }
  .value-box label { display:block; font-size:12px; color:#666; margin-bottom:4px; text-transform:uppercase; }
  .value-box output { font-family:monospace; font-size:16px; color:#333; }
  .preview { width:100%; height:60px; border-radius:4px; border:1px solid #ddd; margin-top:12px; }
</style>
</head>
<body>
<div class="picker">
  <div class="color-band" id="band">
    <div class="crosshair" id="crosshair"></div>
  </div>
  <div class="values">
    <div class="value-box"><label>HSV</label><output id="valHsv">--</output></div>
    <div class="value-box"><label>RGB</label><output id="valRgb">--</output></div>
    <div class="value-box"><label>HEX</label><output id="valHex">--</output></div>
    <div class="value-box preview" id="preview"></div>
  </div>
</div>

<script>
(function() {
  var band = document.getElementById('band');
  var crosshair = document.getElementById('crosshair');
  var valHsv = document.getElementById('valHsv');
  var valRgb = document.getElementById('valRgb');
  var valHex = document.getElementById('valHex');
  var preview = document.getElementById('preview');

  var bandRect = null;
  function updateRect() { bandRect = band.getBoundingClientRect(); }
  updateRect();
  window.addEventListener('resize', updateRect);

  function updateColor(clientX, clientY) {
    if (!bandRect) return;
    var x = Math.max(0, Math.min(bandRect.width, clientX - bandRect.left));
    var y = Math.max(0, Math.min(bandRect.height, clientY - bandRect.top));

    // 更新十字準星位置
    crosshair.style.transform = 'translate(' + (x - 10) + 'px, ' + (y - 10) + 'px)';

    // 計算 HSV
    var h = (x / bandRect.width) * 360;
    var s = 1 - y / bandRect.height; // 頂部飽和度高
    var v = 1 - y / (bandRect.height * 0.5); // 簡化:亮度隨 Y 遞減
    v = Math.max(0, Math.min(1, v));
    s = Math.max(0, Math.min(1, s));

    var rgb = hsvToRgb(h, s, v);
    var hex = rgbToHex(rgb[0], rgb[1], rgb[2]);

    valHsv.textContent = h.toFixed(0) + '°, ' + (s*100).toFixed(0) + '%, ' + (v*100).toFixed(0) + '%';
    valRgb.textContent = 'rgb(' + rgb.join(', ') + ')';
    valHex.textContent = hex.toUpperCase();
    preview.style.background = hex;
  }

  // HSV→RGB 轉換(見上方)
  function hsvToRgb(h, s, v) { ... }
  function rgbToHex(r, g, b) { ... }

  // 滑鼠移動/點擊更新
  band.addEventListener('mousemove', function(e) { updateColor(e.clientX, e.clientY); });
  band.addEventListener('click', function(e) { updateColor(e.clientX, e.clientY); });

  // 初始顯示中心色
  updateColor(bandRect.left + bandRect.width/2, bandRect.top + bandRect.height/2);
})();
</script>
</body>
</html>

演算法細節

  • 色帶水平對應 Hue (0-360°),垂直對應 Saturation/Value
  • 原始碼使用 `filter:alpha(opacity=...)` 產生垂直漸層(IE 專屬),現代版改用 CSS `linear-gradient` 疊加
  • HSV→RGB 採用六區間線性插值,標準演算法
  • HEX 格式化使用 `padStart(2,'0')` 確保兩位數

擴充建議

  • 加入 Alpha 通道支援(HSLA/RGBA/HEX8)
  • 整合色盤(Saturation/Lightness 兩維平面)+ 色相環
  • 支援複製格式(CSS `rgb()`、`hsl()`、Tailwind 類別名)
  • 無障礙:鍵盤操作、ARIA 標籤、高對比模式
copyright © 萬盛學電腦網 all rights reserved