Search code examples
javascriptcolorshsl

Java Script: How can i pull the HSL value when a colour is selected from input type = 'color'?


I am so blank on this idek where to start.

I am trying to make functions that will manipulate the H S L values once I get them. Mainly the light value, which is why I need it in HSL format.

So once I get it, i would idealy like to create

var h = ;
var s = ;
var l = ;

so i can make the functions to manipulate each one

from the type = 'color' pop up selection, once a colour is selected; it does show its RGB value at the bottom, with arrows changing it to hex or HSL - which I want. So I know the information is there, I just don't know how to get it enter image description here


Solution

  • You can't get the HSL representation of the color from the input element directly. Using .value gives you a hex code, which you can then convert to HSL.

    I found the function to convert hex to HSL here.

    function getColor() {
        const input = document.querySelector('#usr-clr')
        const { h, s, l } = hexToHSL(input.value)
        
        console.log(`hsl(${h}, ${s}, ${l})`);
    }
    
    function hexToHSL(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    
        let r = parseInt(result[1], 16);
        let g = parseInt(result[2], 16);
        let b = parseInt(result[3], 16);
    
        r /= 255, g /= 255, b /= 255;
        let max = Math.max(r, g, b), min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;
    
        if (max == min){
            h = s = 0; // achromatic
        } else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch(max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            
            h /= 6;
        }
    
        h = Math.round(h*360);
        s = Math.round(s*100);
        l = Math.round(l*100);
    
        return { h, s, l };
    }
    <input type="color" id="usr-clr" onChange="getColor()">