在四阶渐变中特定百分比位置处找到RGB颜色值

3
问题: 我有一个4个停靠点的渐变,颜色值分别为0%,33%,66%和100%。我想使用百分比找出该渐变中任何一点的颜色值。

我认为我需要一些多停靠点色调插值,但想知道是否有简单的JavaScript方法可以在我开始尝试编写自己的代码之前使用它。

我使用的颜色停靠点:

 //0%
  var stop1 = { r: 25, g: 47, b: 97 };

  //33%
  var stop2 = { r: 75, g: 183, b: 183 };

  //66%
  var stop3 = { r: 237, g: 120, b: 87 };

  //100%
  var stop4 = { r: 209, g: 74, b: 88 };

你有尝试过什么吗?如果有的话,请展示一下你的尝试。谢谢。 - NewToJS
2个回答

2
你可以使用步长间隔的差值,并以正确的比例计算颜色。

How it works.

For example we are looking for the color of 70 % and first, we get the interval of

[66, 100]

Then build the ratio by

  • the delta of percent and the left interval (left)

      70 - 66 => 4
    
  • the delta of the right interval and percent (right)

      100 - 70 => 30
    
  • delta of right and left interval (delta)

      100 - 66 => 34
    
  • with the above generated ratios, it is possible to calculate the right color inbetween of two colors with the parts.

      (color of left interval * right + color of right interval * left) / delta => color
    

Repeat the last step for all colors and return the result.

示例:

* 表示给定的颜色,悬停显示百分比值和RGB值。

function getColor(percent) {
    function getInterval(range) {
        function getRatio(color) {
            return Math.floor((colors[range[0]][color] * right + colors[range[1]][color] * left) / delta);
        }

        var left = percent - range[0],
            right = range[1] - percent,
            delta = range[1] - range[0];

        return { r: getRatio('r'), g: getRatio('g'), b: getRatio('b') };
    }

    return colors[percent] || getInterval(stops.reduce(function (r, a, i, aa) {
        return a < percent ? [a, aa[i + 1]] : r;
    }, [0, 0]));
}

var stops = [0, 33, 66, 100],
    colors = { 0: { r: 25, g: 47, b: 97 }, 33: { r: 75, g: 183, b: 183 },  66: { r: 237, g: 120, b: 87 }, 100: { r: 209, g: 74, b: 88 } },
    i, color, rgb;

for (i = 0; i <= 100; i++) {
    color = getColor(i),
    rgb =  ['r', 'g', 'b'].map(function (k) { return color[k]; });
    document.body.innerHTML += '<span style="color: #fff; background-color: rgb(' + rgb + ');" title="' + (colors[i] ? '* ' : '') + i + ' % rgb(' + rgb.join(', ') + ')">' + (colors[i] ? '*&nbsp;' : '&nbsp;&nbsp;') + '</span>';
}


0

我还发现了一个不错的小工具库,可以用它来轻松搭配各种颜色:chroma.js


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接