admin管理员组

文章数量:1417051

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

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

Share Improve this question asked Jun 15, 2020 at 14:22 Ed.wadoEd.wado 431 silver badge3 bronze badges 1
  • read this css-tricks./converting-color-spaces-in-javascript – Kharel Commented Jun 15, 2020 at 14:31
Add a ment  | 

1 Answer 1

Reset to default 7

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()">

本文标签: