本文介绍了HEX转换为HSL javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试创建HEX到HSL转换器的功能。我知道,首先我应该将HEX转换为RGB,然后再将RGB转换为HSL。我这样做是使用StackOverflow中的一些脚本完成的。 S和L正常工作,但H(色调)不工作。我不知道为什么,这是我的代码:

Hello I'm trying to create HEX to HSL converter function. I know that at first I should convert HEX to RGB and then from RGB to HSL. I've done so using some script from StackOverflow. S and L is working correctly but H (hue) is not. I do not know why, here's my code:

toHSL: function(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

    var r = parseInt(result[1], 16);
    var g = parseInt(result[2], 16);
    var b = parseInt(result[3], 16);

    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var 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;
    }

    s = s*100;
    s = Math.round(s);
    l = l*100;
    l = Math.round(l);

    var colorInHSL = 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
    $rootScope.$emit('colorChanged', {colorInHSL});

当输入为 #ddffdd

则输出为 hsl(0.3333333333333333333,100%,93%)

,但应为 hsl(120,100%,93%)

推荐答案

您忘了将色相乘以360。

You forgot to multiply the hue by 360.

s = s*100;
s = Math.round(s);
l = l*100;
l = Math.round(l);
h = Math.round(360*h);

var colorInHSL = 'hsl(' + h + ', ' + s + '%, ' + l + '%)';

这篇关于HEX转换为HSL javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 04:41