如何获取两种颜色之间的关系?

11

我们使用用户体验团队的样式指南作为参考,通常会用十六进制值记录颜色调色板。例如:

Primary Color : #F27132;
Hover color : #D16605;

基于这些值,我们需要创建我们的样式表(.scss文件)。 scss使用一些函数,如$lighten$darken$saturate$desaturate等。 是否有办法将这些十六进制代码转换为类似的相对格式?例如,

$primary-color : #F27132
$hower-color : $darken($primary-color, 20%)

我认为你不需要任何转换工具来处理这个。这已经由 SCSS 处理了。你的代码应该可以正常工作。 - Akshay Khandelwal
但前提是提供的 Hower 颜色比主要颜色暗20%。 - Akshay Khandelwal
2
你可以将主要颜色分成三个十六进制值(F2、71、32),计算出十进制值,减少20%的亮度(变暗),再转换回十六进制值,这样就得到了你的悬停颜色。 - SaschaP
2
如果用户体验团队已经告诉你要使用什么颜色值,那么使用颜色转换函数的意义何在? - Alohci
1
这些颜色不能随着亮度的变化而相同。H和S值表明它们只有在进行百分比计算时才会改变,L应该是不同的。 - Akshay Khandelwal
显示剩余5条评论
2个回答

1

我曾经有同样的问题,但没有找到好的答案,所以我写了以下代码:

/// Get difference HSL values between two colors 
/// @param {Color} $color1 - Base color
/// @param {Color} $color2 - Second color to compare
/// @param {Bool} $rounded - If returned HSL values must be rounded,
///                          if yes final color will not be exactly the same
/// @return {Debug} - Difference of HSL values between two colors
@mixin getHslDifference( $color1, $color2, $rounded: false ) {
    /* Get HSL values of colors */
    $hue1: hue($color1);
    $sat1: saturation($color1);
    $lig1: lightness($color1);
    $hue2: hue($color2);
    $sat2: saturation($color2);
    $lig2: lightness($color2);

    /* Get hue difference */
    $hueDiff: -( math.div( $hue1, ( $hue2 * 0 + 1 ) )
        - math.div( $hue2, ( $hue1 * 0 + 1 ) ) ); // Strip units
    $hueDiff: if($rounded == true, round($hueDiff), $hueDiff);

    /* Get saturation difference */
    $satDiff: -( $sat1 - $sat2);
    $satDiff: if( $rounded == true, round($satDiff), $satDiff );

    /* Get lightness difference */
    $ligDiff: -( $lig1 - $lig2 );
    $ligDiff: if( $rounded == true, round($ligDiff), $ligDiff );

    @debug "Increase hue by " + $hueDiff;
    @debug "Increase saturation by " + $satDiff;
    @debug "Increase lightness by " + $ligDiff;
}

// 1 - Set the primary color value
$primary-color: #F27132;

// 2 - Get the relationship HSL values between primary and hover colors
@include getHslDifference( $primary-color, #D16605 );

// Will output:
// Debug: Increase hue by 8.8419117647
// Debug: Increase saturation by 7.2537083083%
// Debug: Increase lightness by -15.2941176471%


// 3 - Set the hover color value dynamically (now you can delete previous step
// hexadecimal value of hover color is no more needed)
$hover-color: hsl(
    hue($primary-color) + 8.8419117647,
    saturation($primary-color) + 7.2537083083%,
    lightness($primary-color) + -15.2941176471%
);

@debug $hover-color; // Debug: #d16605

-2

这在使用 Sass 时可以直接运行。但是要注意,当声明函数时需要使用美元符号,但使用函数时不需要。因此,以下内容是正确的:

$hower-color : darken($primary-color, 20%)

1
问题是关于计算20%的方法。 在我的问题中,我只是举了一个例子。 我想要的是,如果我给出2个十六进制值,我需要一个输出, 第二个颜色比第一个颜色更暗或更亮x%。 - Mahesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接