色情報 RGB(赤緑青)とHSL(色相/彩度/明度)を相互に変換

Color-RGB-TO-HSL

RGB (16進数)

RGB

HSL

view source

JavaScript

$(function(){

  var r,g,b,h,s,l,hex;
  var keys = ['r','g','b','h','s','l','hex'];
  var vals = [0,0,0,0,0,0];
  var inputs = {};
  keys.forEach(function(v){
    inputs[v] = $('[name="'+v+'"] input');
    inputs[v].val(0);
  });
  var hex = '#000000';


  var rRangeElement = $('[name="r"] input[type="range"]');
  var gRangeElement = $('[name="g"] input[type="range"]');
  var bRangeElement = $('[name="b"] input[type="range"]');
  var hRangeElement = $('[name="h"] input[type="range"]');
  var sRangeElement = $('[name="s"] input[type="range"]');
  var lRangeElement = $('[name="l"] input[type="range"]');
  

  $('input').on('change', function(){
    var parent = $(this).parent().parent().parent();
    var id = parent.attr('id');
    var name = $(this).parent().attr('name');
    var val = $(this).val();
    $(this).parent().find('input').val(val);

    change(id);
    output();
  });
  


  $('#save').on('click', function(){
    var rgbVal = $('#outputRGB').text();
    var li = $('<li>').css({backgroundColor: rgbVal}).text(rgbVal);
    $('#output ul').append(li);
  });

  $(document).on('click', '#output li', function(){
    var text = $(this).text();
    var match = text.match(/([0-9]*),([0-9]*),([0-9]*)/);
    r = Number(match[1]);
    g = Number(match[2]);
    b = Number(match[3]);
    inputs['r'].val(r);
    inputs['g'].val(g);
    inputs['b'].val(b);
    change('rgb');
    output();
  });

  var change = function(id){
    keys.forEach(function(v, i){
      vals[i] = Number(inputs[v].val()) || inputs[v].val();
    });

    [r,g,b,h,s,l,hex] = vals;
    console.log(vals);
    if(id === 'hex'){
      [r,g,b] = HextoRGB(hex);
    }
    if(id === 'hex' || id === 'rgb'){
      [h,s,l] = RGBtoHSL(r,g,b);
    } else if(id === 'hsl'){
      [r,g,b] = HSLtoRGB(h,s,l);
    }

    hex = RGBtoHex(r,g,b);

    vals = [r,g,b,h,s,l];
    keys.forEach(function(v, i){
      inputs[v].val(vals[i]);
    });
  }

  var outputRange = function(){
    var gradientRGBTemp = 'linear-gradient(to right, rgb({r1},{g1},{b1}), rgb({r2},{g2},{b2}))';

    var rGradient = gradientRGBTemp
      .replace('{r1}', 0)
      .replace('{r2}', 255)
      .replace('{g1}', g)
      .replace('{g2}', g)
      .replace('{b1}', b)
      .replace('{b2}', b);
    rRangeElement.css({background: rGradient});
    var gGradient = gradientRGBTemp
      .replace('{r1}', r)
      .replace('{r2}', r)
      .replace('{g1}', 0)
      .replace('{g2}', 255)
      .replace('{b1}', b)
      .replace('{b2}', b);
    gRangeElement.css({background: gGradient});
    var bGradient = gradientRGBTemp
      .replace('{r1}', r)
      .replace('{r2}', r)
      .replace('{g1}', g)
      .replace('{g2}', g)
      .replace('{b1}', 0)
      .replace('{b2}', 255);
    bRangeElement.css({background: bGradient});

    var sGradient = 'linear-gradient(to right, hsl({h1},{s1}%,{l1}%), hsl({h2},{s2}%,{l2}%))';
    sGradient = sGradient
      .replace('{h1}', h)
      .replace('{h2}', h)
      .replace('{s1}', 0)
      .replace('{s2}', 100)
      .replace('{l1}', l)
      .replace('{l2}', l);
    sRangeElement.css({background: sGradient});

    var lGradient = 'linear-gradient(to right, hsl({h1},{s1}%,{l1}%), hsl({h2},{s2}%,{l2}%), hsl({h3},{s3}%,{l3}%))';
    lGradient = lGradient
    lGradient = lGradient
      .replace('{h1}', h)
      .replace('{h2}', h)
      .replace('{h3}', h)
      .replace('{s1}', s)
      .replace('{s2}', s)
      .replace('{s3}', s)
      .replace('{l1}', 0)
      .replace('{l2}', 50)
      .replace('{l3}', 100);
    lRangeElement.css({background: lGradient});
  }

  var output = function(){
    var rgbVal = 'rgb(' +[r,g,b].join(',')+ ')';
    var hslVal = 'hsl(' +[h,s+'%',l+'%'].join(',')+ ')';
    $('#outputRGB')
      .css({backgroundColor: rgbVal}).text(rgbVal);
    $('#outputHSL')
      .css({backgroundColor: hslVal}).text(hslVal);
    $('[name="hex"] input').val(hex);
    if(l<60){
      $('#output').css({color: '#fff'});
    } else {
      $('#output').css({color: '#000'});
    }
    outputRange();
  }

  var HextoRGB = function (hex){
    var rHex = hex.slice(1, 3);
    var gHex = hex.slice(3, 5);
    var bHex = hex.slice(5, 7);
    var rDec = parseInt(rHex, 16);
    var gDec = parseInt(gHex, 16);
    var bDec = parseInt(bHex, 16);
    return [rDec,gDec,bDec];
  }

  var RGBtoHex = function (r,g,b){
    var rHex = r.toString(16);
    var gHex = g.toString(16);
    var bHex = b.toString(16);
    rHex = ('00' + rHex).slice(-2);
    gHex = ('00' + gHex).slice(-2);
    bHex = ('00' + bHex).slice(-2);
    var hex = '#' + rHex +gHex + bHex;
    return hex;
  }

  var RGBtoHSL = function (r,g,b){
    var h = 0;
    var s = 0;
    var l = 0;
    var ary = [r,g,b];
    ary =ary.sort((a, b) => a - b);

    var max = Math.max(r,g,b);
    var min = Math.min(r,g,b);
    var md = max-min;

    if(md>0){
      if(max === r){
        h = 60 * (g-b) / md;
      } else if(max === g){
        h = 60 * (b-r) / md + 120;
      } else if(max === b){
        h = 60 * (r-g) / md + 240;
      }
    }

    if(h<0){
      h+=360;
    }

    var cnt = (max+min)/2;
    if(cnt<128){
      s = md / (max+min);
    } else  {
      s = md / (510-(max+min));
    }

    l = (max+min)/2;

    h = Math.round(h);
    l = Math.round(l/255 *100);
    s = Math.round(s * 100);
    return [h,s,l];
  }



  var HSLtoRGB = function (h,s,l){
    var r = 0;
    var g = 0;
    var b = 0;
    var max = 0;
    var min = 0;
    if(l<50){
      max = (255/100) * (l + l * (s/100));
      min = (255/100) * (l - l * (s/100));
    } else {
      max = (255/100) * (l + (100-l) * (s/100));
      min = (255/100) * (l - (100-l) * (s/100));
    }
    
    var hi = Math.floor(h/60);
    var mmm = function (hd){
      return min  + (max-min) * (hd/60);
    }
  

    if(hi===0){
      r = max;
      g = mmm(h);
      b = min;
    } else if(hi===1){
      r = mmm(120-h);
      g = max;
      b = min;
    } else if(hi===2){
      r = min;
      g = max;
      b = mmm(h-120);
    } else if(hi===3){
      r = min;
      g = mmm(240-h);
      b = max;
    } else if(hi===4){
      r = mmm(h-240);
      g = min;
      b = max;
    } else if(hi===5){
      r = max;
      g = min;
      b = mmm(360-h);
    }

    r = Math.round(r);
    g = Math.round(g);
    b = Math.round(b);

    return [r,g,b];
  }

  var randomH = Math.floor(Math.random()*360);
  inputs['s'].val(50);
  inputs['l'].val(50);
  inputs['h'].val(randomH).change();

});

CSS

form{
  min-height:100vh;
  padding:10px;
  margin:0 auto;
  max-width:640px;
}

#demo > div{
  margin-top:10px;
}

#output div{
  height:80px;
  line-height:80px;
  font-size:5vmin;
  padding:0 10px;
}

h2{
  font-weight:bold;
}

label{
  display:inline-block;
  width:60px;
}

input,
label{
  height: 32px;
  line-height: 32px;
  vertical-align:middle; 
}

input[type="text"]{
  width:120px;
}

input[type="text"],
input[type="number"]{
  border:0;
  background-color:#eee;
  font-size:18px;
}

label{
  border-right: 12px solid transparent;
}
[name="r"] label{
  border-right: 12px solid #f00;
}
[name="g"] label{
  border-right: 12px solid #0f0;
}
[name="b"] label{
  border-right: 12px solid #00f;
}

input[type="range"]{
  -webkit-appearance: none;
  appearance: none;
  background-color: #c7c7c7;
  width:400px;
  max-width:calc(100% - 150px);
}

input[type="range"]:focus,
input[type="range"]:active {
  outline: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  cursor: pointer;
  position: relative;
  border: none;
  width: 2px;
  height: 36px;
  display: block;
  background-color: #262626;
}


[name="h"] input[type="range"]{
  background: linear-gradient(90deg,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00);
}

#save{
  display:block;
  margin:5px auto;
  width:100%;
  height:40px;
  line-height:40px;
  text-align:center;
  background-color: #999;
  color:#fff;
  border:0;
  font-weight:bold;
  font-size:4vmin;
  border-radius:16px;
  cursor:pointer;
}

#output ul {
  display:flex;
  flex-wrap:wrap;
}
#output ul li{
  width:25%;
  padding:10px 0;
}

HTML

ページのソースを表示 : Ctrl+U , DevTools : F12

view-source:https://hi0a.com/demo/-js/js-color-rgb-to-hsl/

ABOUT

hi0a.com 「ひまアプリ」は無料で遊べるミニゲームや便利ツールを公開しています。

プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。

必要な機能の関数をコピペ利用したり勉強に活用できます。

プログラムの動作サンプル結果は画面上部に出力表示されています。

環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。

画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。

動く便利なものが好きなだけで技術自体に興味はないのでコードは汚いです。

途中放置や実験状態、仕様変更、API廃止等で動かないページもあります。