js 正則判斷顏色值,HEX轉RGB,HSL轉RGB

小弟調調發表於2017-08-16

顏色值判斷

/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(`#009a61`)
/^rgb/.test(`rgb(0, 154, 97)`)
/^hsl/.test(`hsl(0, 0%, 20%)`)

HEX顏色值轉換為RGB

// Colors
function hexToRgb(hexValue) {
  const rgx = /^#?([a-fd])([a-fd])([a-fd])$/i;
  const hex = hexValue.replace(rgx, (m, r, g, b) => r + r + g + g + b + b );
  const rgb = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
  const r = parseInt(rgb[1], 16);
  const g = parseInt(rgb[2], 16);
  const b = parseInt(rgb[3], 16);
  return `rgb(${r},${g},${b})`;
}

HSL顏色值轉換為RGB

HSL 為 色相,飽和度,亮度。

function hslToRgb(hslValue) {
  const hsl = /hsl((d+),s*([d.]+)%,s*([d.]+)%)/g.exec(hslValue);
  const h = parseInt(hsl[1]) / 360;
  const s = parseInt(hsl[2]) / 100;
  const l = parseInt(hsl[3]) / 100;
  function hue2rgb(p, q, t) {
    if (t < 0) t += 1;
    if (t > 1) t -= 1;
    if (t < 1/6) return p + (q - p) * 6 * t;
    if (t < 1/2) return q;
    if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
    return p;
  }
  let r, g, b;
  if (s == 0) {
    r = g = b = l;
  } else {
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    const p = 2 * l - q;
    r = hue2rgb(p, q, h + 1/3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1/3);
  }
  return `rgb(${r * 255},${g * 255},${b * 255})`;
}

程式碼來源:https://github.com/juliangarn…

相關文章