将Hsl转换为rgb和十六进制

convert Hsl to rgb and hex

本文关键字:十六进制 rgb Hsl 转换      更新时间:2023-09-26

我需要一个颜色转换器来将hsl转换为rgb和十六进制值。我会做类似的事情。我使用的是jquery和jquery ui范围滑块。这是我的代码:

$(function() {
    $( "#hsl_hue_range" ).slider({
        min: 0,
        max: 100,
        value: 0,
        range: false,
        animate:"slow",
        orientation: "horizontal",
        slide: function( event, ui ) {
            var hsl_hue = ui.value;
        }
    });
});
$(function() {
    $( "#hsl_saturation_range" ).slider({
        min: 0,
        max: 100,
        value: 0,
        range: false,
        animate:"slow",
        orientation: "horizontal",
        slide: function( event, ui ) {
            var hsl_saturation = ui.value;
        }
    });
});
$(function() {
    $( "#hsl_light_range" ).slider({
        min: 0,
        max: 100,
        value: 0,
        range: false,
        animate:"slow",
        orientation: "horizontal",
        slide: function( event, ui ) {
            var hsl_light = ui.value;
        }
    });
});

我想要这样的解决方案:

转换器的输入可以由变量给出。如CCD_ 1 hsl_saturation CCD_。

有办法做到这一点吗
如果没有办法,我该怎么办?

新方法(灵感来自@Kamil Kiełczewski解决方案)
接受degree, percentage, percentage并返回css hex color:

function hslToHex(h, s, l) {
  l /= 100;
  const a = s * Math.min(l, 1 - l) / 100;
  const f = n => {
    const k = (n + h / 30) % 12;
    const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
    return Math.round(255 * color).toString(16).padStart(2, '0');   // convert to Hex and prefix "0" if needed
  };
  return `#${f(0)}${f(8)}${f(4)}`;
}

示例:

hslToHex(360, 100, 50)  // "#ff0000" -> red

原始版本:(仍然可以,只是更长)

获取degree, percentage, percentage并返回css hex color:

function hslToHex(h, s, l) {
  h /= 360;
  s /= 100;
  l /= 100;
  let r, g, b;
  if (s === 0) {
    r = g = b = l; // achromatic
  } else {
    const 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;
    };
    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);
  }
  const toHex = x => {
    const hex = Math.round(x * 255).toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

示例:

hslToHex(360, 100, 50)  // "#ff0000" -> red

最短

试试这个(wiki,错误分析,更多:rgb2hsl,hsv2rgb rgb2hsv和hsl2hsv)

// input: h in [0,360] and s,v in [0,1] - output: r,g,b in [0,1]
function hsl2rgb(h,s,l) 
{
  let a= s*Math.min(l,1-l);
  let f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1);
  return [f(0),f(8),f(4)];
}   

要计算hsl2hex,请使用rgb2hex(...hsl2rgb(30,1,0.5))。要将字符串从格式(例如rgb(255, 255, 255))转换为十六进制,请使用hsl_hue0(处理空字符串大小写),如下所示

// oneliner version
let hsl2rgb = (h,s,l, a=s*Math.min(l,1-l), f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1)) => [f(0),f(8),f(4)];
// r,g,b are in [0-1], result e.g. #0812fa.
let rgb2hex = (r,g,b) => "#" + [r,g,b].map(x=>Math.round(x*255).toString(16).padStart(2,0) ).join('');
// hexStr e.g #abcdef, result "rgb(171,205,239)"
let hexStr2rgb  = (hexStr) => `rgb(${hexStr.substr(1).match(/../g).map(x=>+`0x${x}`)})`;
// rgb - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
let rgbStrToHex= rgb=> '#'+rgb.match(/'d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

console.log(`hsl: (30,0.2,0.3) --> rgb: (${hsl2rgb(30,0.2,0.3)}) --> hex: ${rgb2hex(...hsl2rgb(30,0.2,0.3))}`);
console.log(`rgb: ${hexStr2rgb("#ff647b")} --> hex: ${rgbStrToHex("rgb(255,100, 123)")}`)

// ---------------
// UX
// ---------------
rgb= [0,0,0];
hs= [0,0,0];
let $ = x => document.querySelector(x);
function changeRGB(i,e) {
  rgb[i]=e.target.value/255;
  hs = rgb2hsl(...rgb);
  refresh();
}
function changeHS(i,e) {
  hs[i]=e.target.value/(i?255:1);
  rgb= hsl2rgb(...hs);
  refresh();
}
function refresh() {
  rr = rgb.map(x=>x*255|0).join(', ')
  hh = rgb2hex(...rgb);
  tr = `RGB: ${rr}`
  th = `HSL: ${hs.map((x,i)=>i? (x*100).toFixed(2)+'%':x|0).join(', ')}`
  thh= `HEX: ${hh}`
  $('.box').style.backgroundColor=`rgb(${rr})`;  
  $('.infoRGB').innerHTML=`${tr}`;  
  $('.infoHS').innerHTML =`${th}'n${thh}`;  
  
  $('#r').value=rgb[0]*255;
  $('#g').value=rgb[1]*255;
  $('#b').value=rgb[2]*255;
  
  $('#h').value=hs[0];
  $('#s').value=hs[1]*255;
  $('#l').value=hs[2]*255;  
}
function rgb2hsl(r,g,b) {
  let a=Math.max(r,g,b), n=a-Math.min(r,g,b), f=(1-Math.abs(a+a-n-1)); 
  let h= n && ((a==r) ? (g-b)/n : ((a==g) ? 2+(b-r)/n : 4+(r-g)/n)); 
  return [60*(h<0?h+6:h), f ? n/f : 0, (a+a-n)/2];
}
refresh();
.box {
  width: 50px;
  height: 50px;
  margin: 20px;
}
body {
    display: flex;
}
<div>
<input id="r" type="range" min="0" max="255" oninput="changeRGB(0,event)">R<br>
<input id="g" type="range" min="0" max="255" oninput="changeRGB(1,event)">G<br>
<input id="b" type="range" min="0" max="255" oninput="changeRGB(2,event)">B<br>
<pre class="infoRGB"></pre>
</div> 
<div>
<div class="box hsl"></div>
</div>
<div>
<input id="h" type="range" min="0" max="360" oninput="changeHS(0,event)">H<br>
<input id="s" type="range" min="0" max="255" oninput="changeHS(1,event)">S<br>
<input id="l" type="range" min="0" max="255" oninput="changeHS(2,event)">L<br>
<pre class="infoHS"></pre><br>
</div>

HSL到RGB:

/**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes h, s, and l are contained in the set [0, 1] and
     * returns r, g, and b in the set [0, 255].
     *
     * @param   {number}  h       The hue
     * @param   {number}  s       The saturation
     * @param   {number}  l       The lightness
     * @return  {Array}           The RGB representation
     */
    function hslToRgb(h, s, l){
        var r, g, b;
        if(s == 0){
            r = g = b = l; // achromatic
        }else{
            var hue2rgb = 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;
            }
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }
        return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
    }


您可以在这里找到更多信息-HSL到RGB颜色转换

解决此问题的另一种方法是利用现代浏览器的window.getComputedStyle功能:

  1. 在页面上创建一个元素(它可以隐藏,例如display:none,但似乎会抑制不透明度/"A"值的输出)

  2. 使用您选择的表示设置该元素的颜色值属性,例如e.style.color = 'hsla(100, 50%, 75%, 0.8)';(甚至命名颜色,如'rebeccapurple'

  3. 使用window.getComputedStyle(e).color读回该值。它将是形式为rgb(r,g,b)rgba(r,g,b,a)的字符串。

CodePen 上的实时演示

我制作了一个可以轻松转换颜色的小库。

这是我的HSL到RGB方法,它使用了库中的其他一些实用方法:

Color.hslToRgb = function(hsl, formatted) {
  var a, b, g, h, l, p, q, r, ref, s;
  if (isString(hsl)) {
    if (!hsl.match(Color.HSL_REGEX)) {
      return;
    }
    ref = hsl.match(/hsla?'((.+?)')/)[1].split(',').map(function(value) {
      value.trim();
      return parseFloat(value);
    }), h = ref[0], s = ref[1], l = ref[2], a = ref[3];
  } else if ((isObject(hsl)) && (hasKeys(hsl, ['h', 's', 'l']))) {
    h = hsl.h, s = hsl.s, l = hsl.l, a = hsl.a;
  } else {
    return;
  }
  h /= 360;
  s /= 100;
  l /= 100;
  if (s === 0) {
    r = g = b = l;
  } else {
    q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    p = 2 * l - q;
    r = Color.hueToRgb(p, q, h + 1 / 3);
    g = Color.hueToRgb(p, q, h);
    b = Color.hueToRgb(p, q, h - 1 / 3);
  }
  return getRgb(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a, formatted);
};

如果你不想使用npm,也可以在GitHub上找到lib。

我最近有理由解决这个问题,并提出了一个基于画布的解决方案。我把它记录在这里只是为了子孙后代。

在我的情况下,我还需要考虑到在给定一系列背景色和半透明alpha通道的情况下对转换的累积影响。。。

var HSL2COLOR = function () {
    return function (hsl, bg) {
        function checkHex(v) {
            return 1 === v.length ? '0'+v : v;
        }
        var data, r, g, b, a,
        cnv = document.createElement('canvas'),
        ctx = cnv.getContext('2d'),
        alpha = /a'(/.test(hsl),
        output = {};
        return cnv.width = cnv.height = 1,
        bg && (ctx.fillStyle = bg, ctx.fillRect(0, 0, 1, 1)),
        ctx.fillStyle = hsl,
        ctx.fillRect(0, 0, 1, 1),
        data = ctx.getImageData(0, 0, 1, 1).data,
        r = data[0],
        g = data[1],
        b = data[2],
        a = (data[3] / 255).toFixed(2),
        alpha ? (output.hsla = hsl, bg ? output.rgb = 'rgb('+r+','+g+','+b+')' : output.rgba = 'rgb('+r+','+g+','+b+','+a+')')  : (output.hsl = hsl, output.rgb = 'rgb('+r+','+g+','+b+')'),
        output.hex = '#'+checkHex(r.toString(16))+checkHex(g.toString(16))+checkHex(b.toString(16)),
        output;
    };
}();
// hsl: no alpha-channel + no background color
console.log(HSL2COLOR('hsl(170, 60%, 45%)'));
/*=> { 
        hsl: "hsl(170, 60%, 45%)", 
        rgb: "rgb(45,183,160)", 
        hex: "#2db7a0" 
     }
*/
// hsla: alpha-channel + no background color 
console.log(HSL2COLOR('hsla(170, 60%, 45%, 0.35)'));
/*=> {
        hsla: "hsla(170, 60%, 45%, 0.35)",
        rgba: "rgb(42,183,160,0.35)", 
        hex: "#2ab7a0" 
     }
*/
// hsla: alpha-channel + background color
console.log(HSL2COLOR('hsla(170, 60%, 45%, 0.35)','#f00'));
/*=> {
        hsla: "hsla(170, 60%, 45%, 0.35)",
        rgb: "rgb(181,64,56)", 
        hex: "#b54038" 
     }
*/

从上面的结果中可以看出,当输入中有alpha通道但没有指定背景颜色时,HEX值并不是特别具有代表性,因为画布基本上看到的是黑色的透明背景。尽管如此,rgba值保持一致。

不管怎样,我实现了我需要的,也许这对某个人来说会有一些用处。

BP

或者你可以npm install color-convert而不重新发明轮子。

const convert = require('color-convert')
const hex = '#' + convert.hsl.hex(96, 48, 59) // convert hsl to hex
const rgb = convert.hsl.rgb(96, 48, 59) // convert hsl to rgb

生活有时很简单。

来自@icl7126的答案,

您可以添加另一个函数参数以包括alpha

function hsl2hex(h,s,l,alpha) {
    l /= 100;
    const a = s * Math.min(l, 1 - l) / 100;
    const f = n => {
      const k = (n + h / 30) % 12;
      const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
      return Math.round(255 * color).toString(16).padStart(2, '0');   
      // convert to Hex and prefix "0" if needed
    };
  //alpha conversion
  alpha = Math.round(alpha * 255).toString(16).padStart(2, '0');
  return `#${f(0)}${f(8)}${f(4)}${alpha}`;
} 

最终解决方案:

function stringAsColor(string, saturation = 100, lightness = 50) {
    let hash = 0;
    for (let i = 0; i < string.length; i++) {
        hash = string.charCodeAt(i) + ((hash << 5) - hash);
        hash = hash & hash;
    }
    const hslToHex = function (h, s, l) {
        l /= 100;
        const a = s * Math.min(l, 1 - l) / 100;
        const f = n => {
            const k = (n + h / 30) % 12;
            const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
            return Math.round(255 * color).toString(16).padStart(2, '0');
        };
        return ['#', f(0), f(8), f(4)].join('');
    };
    return hslToHex(Math.abs(hash % 360), saturation, lightness);
}

Ussage:

stringAsColor('abc');          // -> '#0019ff'
stringAsColor('abc', 100, 20); // -> '#000a66'