Html 我怎样才能得到两种颜色中间的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14482226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:11:49  来源:igfitidea点击:

How can I get the color halfway between two colors?

htmlcss

提问by Deleplace

I have two colors:

我有两种颜色:

#15293E
#012549

How can I find the color that is half way in between them? Is there some way to do this calculation?

我怎样才能找到它们中间的颜色?有没有办法做这个计算?

回答by Deleplace

As Mr Lister just said, it is easy to automate the calculation with any programming language :

正如 Lister 先生刚才所说,使用任何编程语言都可以轻松实现自动计算:

  1. Separate your two colors into their 3 color numbers for Red, Green, Blue: (r1,g1,b1) and (r2,g2,b2).
    • For example #15293E, #012549 become ("15", "29", "3E"), ("01", "25", "49")

  2. Convert each color string into an integer, specifying explicitly that you are parsing a hexadecimal-basedrepresentation of a number.
    • For example ("15", "29", "3E") becomes (21, 41, 62)

  3. Calculate the average (r',g',b') = ( (r1+r2)/2, (g1+g2)/2, (b1+b2)/2 ).
    • For example ( (21+1)/2, (41+37)/2, (62+73)/2) = (11, 39, 67)

  4. Convert them again to strings , specifying explicitly that you are generating two-digithexadecimal representations (pad with a zero when necessary).
    • For example (11, 39, 67) -> ("0B", "27", "43")

  5. Concatenate a hash character followed by the 3 strings
    • For example ("0B", "27", "43") -> "#0B2743"
  1. 将您的两种颜色分成红、绿、蓝的 3 个色号:(r1,g1,b1) 和 (r2,g2,b2)。
    • 例如 #15293E, #012549 变成 ("15", "29", "3E"), ("01", "25", "49")

  2. 将每个颜色字符串转换为整数,明确指定您正在解析数字的基于十六进制的表示形式。
    • 例如 ("15", "29", "3E") 变成 (21, 41, 62)

  3. 计算平均值 (r',g',b') = ( (r1+r2)/2, (g1+g2)/2, (b1+b2)/2 )。
    • 例如 ( (21+1)/2, (41+37)/2, (62+73)/2) = (11, 39, 67)

  4. 再次将它们转换为 strings ,明确指定您正在生成两位十六进制表示(必要时用零填充)。
    • 例如 (11, 39, 67) -> ("0B", "27", "43")

  5. 连接一个哈希字符,后跟 3 个字符串
    • 例如 ("0B", "27", "43") -> "#0B2743"

Edit :Implementation is not "very easy" as I initially stated. I took the time to write the code in several languages on Programming-Idioms.

编辑:正如我最初所说的那样,实施并不“非常容易”。我花时间在 Programming-Idioms 上用多种语言编写代码。

回答by hjpotter92

I use this website to do this task for me: ColorBlender.

我使用这个网站为我完成这个任务:ColorBlender

The mid-color will be #0B2744.

中间色将为#0B2744

回答by ScottS

With LESS

If you use the latest LESS CSS preprocessorthen you'll notice there is a function (mix()) that does this:

如果您使用最新的LESS CSS 预处理器,那么您会注意到有一个函数 ( mix()) 执行此操作:

mix(#15293E, #012549, 50%)

Outputs: #0b2744.

输出:#0b2744

回答by Neil Slater

If you need to do this generically, and expect the middle colour to be visually accurate in more cases (i.e. the visual colour and tone of the mid point should "look right" to a human viewer), then as suggested above you may want to convert from RGB to HSV or HSL before calculating the mid point, and then convert back afterwards. This may differ significantly from averaging RGB values directly.

如果您需要一般性地执行此操作,并希望在更多情况下中间颜色在视觉上准确(即,中点的视觉颜色和色调对人类观察者来说应该“看起来正确”),那么如上所述,您可能想要在计算中点之前从 RGB 转换为 HSV 或 HSL,然后再转换回来。这可能与直接平均 RGB 值有很大不同。

Here is some JavaScript code for the conversion to/from HSL that I found on a brief search, and that on a brief check appears to do the right thing:

这是我在简短搜索中找到的一些用于与 HSL 之间转换的 JavaScript 代码,并且在简短的检查中似乎做了正确的事情:

github.com/mHymanson/mjiHymanson.github.com/blob/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.txt

github.com/mHymanson/mjiHymanson.github.com/blob/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.txt

https://web.archive.org/web/20170919064926/https://github.com/mHymanson/mjiHymanson.github.com/blob/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.txt

https://web.archive.org/web/20170919064926/https://github.com/mHymanson/mjiHymanson.github.com/blob/master/2008/02/rgb-to-hsl-and-rgb-to- hsv-color-model-conversion-algorithms-in-javascript.txt

Just apply the rgbToHsl function to your two r,g,b colour vectors, average the two resulting vectors, and apply hslToRgb to that . . .

只需将 rgbToHsl 函数应用于您的两个 r,g,b 颜色向量,对两个结果向量求平均值,然后将 hslToRgb 应用于该向量。. .

回答by Hymanson

Handy-Dandy Function

Handy-Dandy 功能

function padToTwo(numberString) {
    if (numberString.length < 2) {
        numberString = '0' + numberString;
    }
    return numberString;
}

function hexAverage() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function (previousValue, currentValue) {
        return currentValue
            .replace(/^#/, '')
            .match(/.{2}/g)
            .map(function (value, index) {
                return previousValue[index] + parseInt(value, 16);
            });
    }, [0, 0, 0])
    .reduce(function (previousValue, currentValue) {
        return previousValue + padToTwo(Math.floor(currentValue / args.length).toString(16));
    }, '#');
}

console.log(hexAverage('#111111', '#333333')); // => #222222
console.log(hexAverage('#111111', '#222222')); // => #191919
console.log(hexAverage('#111111', '#222222', '#333333')); // => #222222
console.log(hexAverage('#000483', '#004B39')); // => #00275e

回答by Rested

Like this:

像这样:

function colourGradientor(p, rgb_beginning, rgb_end){

    var w = p * 2 - 1;


    var w1 = (w + 1) / 2.0;
    var w2 = 1 - w1;

    var rgb = [parseInt(rgb_beginning[0] * w1 + rgb_end[0] * w2),
        parseInt(rgb_beginning[1] * w1 + rgb_end[1] * w2),
            parseInt(rgb_beginning[2] * w1 + rgb_end[2] * w2)];
    return rgb;
};

where p is a value between 0 and 1 specifying how far through the gradient the colour should be and rgb_beginning is the from colour and rgb_end is the to colour. Both are [r,g,b] arrays so you'll have to convert from hex first. This is a simplified version of LESS's mix function which I think is from SASS. For the poster p would be 0.5

其中 p 是一个介于 0 和 1 之间的值,指定颜色应该通过渐变多远,rgb_beginning 是起始颜色,rgb_end 是终止颜色。两者都是 [r,g,b] 数组,因此您必须先从十六进制转换。这是我认为来自 SASS 的 LESS 混合功能的简化版本。对于海报 p 将是 0.5

回答by Dan Levin

i just wrote a function that calculates colors between two colors so here it is in case somebody needs it, i think it's quite short and readable, it accepts two colors in hex strings, and the number of colors to calculate in between, returns the colors in an array of hex strings

我刚刚写了一个函数来计算两种颜色之间的颜色,所以这里是以防万一有人需要它,我认为它很短且可读,它接受十六进制字符串中的两种颜色,并且在两者之间计算颜色的数量,返回颜色在十六进制字符串数组中

i took the rgbToHex and hexToRgb functions from here

我从这里获取了 rgbToHex 和 hexToRgb 函数

Hope this helps!

希望这可以帮助!

function rgbToHex(r, g, b) {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      }
    : null;
}

// returns an array of startColor, colors between according to steps, and endColor
function getRamp(startColor, endColor, steps) {
  var ramp = [];

  ramp.push(startColor);

  var startColorRgb = hexToRgb(startColor);
  var endColorRgb = hexToRgb(endColor);

  var rInc = Math.round((endColorRgb.r - startColorRgb.r) / (steps+1));
  var gInc = Math.round((endColorRgb.g - startColorRgb.g) / (steps+1));
  var bInc = Math.round((endColorRgb.b - startColorRgb.b) / (steps+1));

  for (var i = 0; i < steps; i++) {
    startColorRgb.r += rInc;
    startColorRgb.g += gInc;
    startColorRgb.b += bInc;

    ramp.push(rgbToHex(startColorRgb.r, startColorRgb.g, startColorRgb.b));
  }
  ramp.push(endColor);

  return ramp;
}

回答by Eric Johnson

I found an npm module that does this: https://www.npmjs.com/package/color-between

我找到了一个执行此操作的 npm 模块:https: //www.npmjs.com/package/color-between

Here's some example usage:

下面是一些示例用法:

const colorBetween = require('color-between');

// rgb format
colorBetween('rgb(255, 255, 255)', 'rgb(0, 0, 0)', 0.5, 'rgb');
// output: 'rgb(128, 128, 128)'

// rgba format
colorBetween('rgba(255, 255, 255, .2)', 'rgba(0, 0, 0, .8)', 0.5, 'rgb');
// output: 'rgba(128, 128, 128, 0.5)

// hex format
colorBetween('#fff', '#000', 0.5, 'hex');
// output: '#808080'

// mixed format
colorBetween('#fff', 'rgb(0, 0, 0)', 0.5, 'hsl');
output: 'hsl(0, 0%, 50%)'

回答by Dave Haigh

If you so wished you could do it yourself with windows calculator.

如果您愿意,可以使用 Windows 计算器自己完成。

  1. Open Windows Calculator > View > Programmer
  2. Choose the Hex option
  3. Enter the Hex value
  4. Switch to Dec and write down the value given
  5. Repeat for steps 2-4 for the second hex value
  6. Calculate the average by adding the two Dec numbers and dividing by 2
  7. Enter this value into calculator with the Dec option selected then switch to the hex option and voila
  1. 打开 Windows 计算器 > 查看 > 程序员
  2. 选择十六进制选项
  3. 输入十六进制值
  4. 切换到 Dec 并记下给定的值
  5. 对第二个十六进制值重复步骤 2-4
  6. 通过将两个 Dec 数字相加并除以 2 来计算平均值
  7. 将此值输入到选择 Dec 选项的计算器中,然后切换到十六进制选项,瞧

Example:

例子:

  • 15293E (HEX) = 1386814 (DEC)
  • 012549 (HEX) = 75081 (DEC)
  • Mid Point = (1386814+75081)/2
  • Mid Point = 730947 (DEC)
  • 730947 (DEC) = 0B2743 (HEX)
  • #0B2743
  • 15293E(十六进制)= 1386814(十二月)
  • 012549 (十六进制) = 75081 (十二月)
  • 中点 = (1386814+75081)/2
  • 中点 = 730947 (DEC)
  • 730947 (12 月) = 0B2743 (十六进制)
  • #0B2743

or use ColorBlender as mentioned above ;)

或使用上面提到的 ColorBlender ;)