javascript 如何使用javascript按百分比从渐变中获取颜色值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30143082/
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-10-28 11:47:28  来源:igfitidea点击:

How to get color value from gradient by percentage with javascript?

javascriptjquerycsscolorslinear-gradients

提问by passatgt

I have a fixed width div with gradient applied using css. I want to build slider based color picker based on this gradient.

我有一个固定宽度的 div,使用 css 应用了渐变。我想基于此渐变构建基于滑块的颜色选择器。

When i drag the slider i calculate the percentage position, and i want to get the hex or rgb color code based on this value.

当我拖动滑块时,我会计算百分比位置,并且我想根据此值获取十六进制或 rgb 颜色代码。

My idea was to create an array with the start/stop positions and colors defined, then find two values from this array based on the slider position, then somehow find the color between: this is where i can't move forward.

我的想法是创建一个定义了开始/停止位置和颜色的数组,然后根据滑块位置从该数组中找到两个值,然后以某种方式找到两者之间的颜色:这是我无法前进的地方。

Demo: http://jsfiddle.net/pdu8rpfv/

演示:http: //jsfiddle.net/pdu8rpfv/

var gradient = [
    [
        0,
        'ff0000'
    ],
    [
        28,
        '008000'
    ],
    [
        72,
        '0000ff'
    ],
    [
        100,
        'ff0000'
    ]
];
$( "#slider" ).slider({
    min: 1,
    slide: function( event, ui ) {

        var colorRange = []
        $.each(gradient, function( index, value ) {
            if(ui.value<=value[0]) {
                colorRange = [index-1,index]
                return false;
            }
        });

        $('#result').css("background-color", 'red');

    }
});

回答by passatgt

I was able to solve this issue using this function, which is based on the less.js function: http://lesscss.org/functions/#color-operations-mix

我能够使用这个基于less.js 函数的函数来解决这个问题:http://lesscss.org/functions/#color-operations-mix

function pickHex(color1, color2, weight) {
    var w1 = weight;
    var w2 = 1 - w1;
    var rgb = [Math.round(color1[0] * w1 + color2[0] * w2),
        Math.round(color1[1] * w1 + color2[1] * w2),
        Math.round(color1[2] * w1 + color2[2] * w2)];
    return rgb;
}

I just simply need to pass the two closest color codes from the gradient array and the ratio where the slider handle is located(which can be calculated easily with the help of the slider width). Here is the live example:

我只需要从渐变数组中传递两个最接近的颜色代码和滑块手柄所在的比率(可以在滑块宽度的帮助下轻松计算)。这是现场示例:

http://jsfiddle.net/vksn3yLL/

http://jsfiddle.net/vksn3yLL/

回答by 538ROMEO

This is another way to convert percentage to color

这是将百分比转换为颜色的另一种方法

This exemple make a displayed value change from red to green depending on it's value (like for example in excel conditional formating):

本示例根据其值将显示值从红色变为绿色(例如在 excel 条件格式中):

function(percentValue) {
  $(`#output`)
    // print the value
    .html(percentValue)
    // colorize the text, more red if it's close to 0
    // and more green as it approach 100
    .css({color: `rgb(${(100 - percent) *2.56}, ${percent *2.56},0)`})
}

Please see demo below:

请看下面的演示:

$('button').click( e => {
  const percent = Math.floor(Math.random()*100);
  const newElm = $(`<b>${percent}</b><br>`)
  .css({color: `rgb(${(100 - percent) *2.56},${percent *2.56},0)`})
  $('body').append(newElm);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click to make new percentage</button><br>

回答by Luis Limas

Three color gradient

三色渐变

Just in case someone wants a 3 color gradient, here's an example using red, yellow and green:

以防万一有人想要 3 色渐变,这里有一个使用红色、黄色和绿色的示例:

enter image description here

在此处输入图片说明

The github JS code for the colorGradientfunction is available here.

colorGradient函数的 github JS 代码可在此处获得

function colorGradient(fadeFraction, rgbColor1, rgbColor2, rgbColor3) {
    var color1 = rgbColor1;
    var color2 = rgbColor2;
    var fade = fadeFraction;

    // Do we have 3 colors for the gradient? Need to adjust the params.
    if (rgbColor3) {
      fade = fade * 2;

      // Find which interval to use and adjust the fade percentage
      if (fade >= 1) {
        fade -= 1;
        color1 = rgbColor2;
        color2 = rgbColor3;
      }
    }

    var diffRed = color2.red - color1.red;
    var diffGreen = color2.green - color1.green;
    var diffBlue = color2.blue - color1.blue;

    var gradient = {
      red: parseInt(Math.floor(color1.red + (diffRed * fade)), 10),
      green: parseInt(Math.floor(color1.green + (diffGreen * fade)), 10),
      blue: parseInt(Math.floor(color1.blue + (diffBlue * fade)), 10),
    };

    return 'rgb(' + gradient.red + ',' + gradient.green + ',' + gradient.blue + ')';
}

Demo:

演示:

// Gradient Function
function colorGradient(fadeFraction, rgbColor1, rgbColor2, rgbColor3) {
    var color1 = rgbColor1;
    var color2 = rgbColor2;
    var fade = fadeFraction;

    // Do we have 3 colors for the gradient? Need to adjust the params.
    if (rgbColor3) {
      fade = fade * 2;

      // Find which interval to use and adjust the fade percentage
      if (fade >= 1) {
        fade -= 1;
        color1 = rgbColor2;
        color2 = rgbColor3;
      }
    }

    var diffRed = color2.red - color1.red;
    var diffGreen = color2.green - color1.green;
    var diffBlue = color2.blue - color1.blue;

    var gradient = {
      red: parseInt(Math.floor(color1.red + (diffRed * fade)), 10),
      green: parseInt(Math.floor(color1.green + (diffGreen * fade)), 10),
      blue: parseInt(Math.floor(color1.blue + (diffBlue * fade)), 10),
    };

    return 'rgb(' + gradient.red + ',' + gradient.green + ',' + gradient.blue + ')';
}
  
// Implementation sample
var spans = $('.gradient-test');
var count = spans.length, color;
var color1 = {
  red: 19, green: 233, blue: 19
};
var color2 = {
  red: 255, green: 0, blue: 0
};
var color3 = {
  red: 255, green: 255, blue: 0
};
$('.gradient-test').each(function(i, span) {
  var g = Math.round(((i+1) * 100) / count);
  if (g < 10){
    g = '0' + g;
  }
  g = +('0.' + g)
  color = colorGradient(g, color1, color2, color3);
  $(span).css('background-color', color);
});
.gradient-test {
  width: 1rem;
  height: 1rem;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>
<span class="gradient-test"></span>