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

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

本文介绍了如何使用javascript从渐变百分比中获取颜色值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我拖动滑块时,我计算百分比位置,我想得到十六进制或rgb颜色代码基于这个值。

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.

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

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.

演示:

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');

    }
});


推荐答案

我能够使用此功能解决此问题,它基于less.js函数:

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

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:

这篇关于如何使用javascript从渐变百分比中获取颜色值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:08