如何使用javascript按百分比从渐变中获取颜色值? [英] How to get color value from gradient by percentage with javascript?

查看:23
本文介绍了如何使用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.

演示: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');

    }
});

推荐答案

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

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:

http://jsfiddle.net/vksn3yLL/

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆