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

后端 未结 5 1127
离开以前
离开以前 2020-12-08 10:54

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

When i drag the slider i calculate the pe

5条回答
  •  无人及你
    2020-12-08 11:41

    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/

提交回复
热议问题