如何使用 jQuery 查找颜色之间的差异

How to find colour variations between one and another with jQuery

如果我有颜色 #FF0CB6#EC9CF4,我如何在它们之间找到 10 种变化(就像渐变那样)并最终将它们放入数组中?

类似于此网站的功能:http://www.perbang.dk/rgbgradient/

有人知道如何解决这个问题吗?

您可以使用 'RainbowVis-JS' 并获得两个颜色十六进制代码之间的十六进制颜色代码。

var numberOfItems = 8;
var rainbow = new Rainbow(); 
rainbow.setNumberRange(1, numberOfItems);
rainbow.setSpectrum('red', 'black');
var s = '';
for (var i = 1; i <= numberOfItems; i++) {
    var hexColour = rainbow.colourAt(i);
    s += '#' + hexColour + ', ';
}
document.write(s); 

要使用普通 javascript,您需要做两件事。首先,您需要将十六进制颜色转换为整数。我将函数命名为 colorStrToIntArray:

function colorStrToIntArray(color) {
    // strip '#'
    if (color.length == 4 || color.length == 7) {
        color = color.substr(1);
    }

    // for colors like '#fff'
    if (color.length == 3) {
        var r = parseInt(color.substr(0, 1) + color.substr(0, 1), 16),
            g = parseInt(color.substr(1, 1) + color.substr(1, 1), 16),
            b = parseInt(color.substr(2, 1) + color.substr(2, 1), 16);

        return [r, g, b];
    } 

    // for colors like '#ffffff'
    else if (color.length == 6) {
        return [
            parseInt(color.substr(0, 2), 16), 
            parseInt(color.substr(2, 2), 16), 
            parseInt(color.substr(4, 2), 16)
        ];
    }

    return false;
}

在第二步中,您只需计算整数之间的差值。瞧,有你的颜色:

function calculateSteps(color1, color2, steps) {
    var output = [],
        start = colorStrToIntArray(color1),
        end = colorStrToIntArray(color2);

    var calculate = function(start, end, step) {
        return (start + Math.round((end - start) * (step / (steps / 2))));
    };

    for ( var i = 0; i < steps; i++ ) {
        var color = [0, 0, 0];

        color[0] = calculate(start[0], end[0], i);
        color[1] = calculate(start[1], end[1], i);
        color[2] = calculate(start[2], end[2], i);

        output.push(color);
    }

    return output;
}

代码可能会被缩短,但它正在运行。 :)

Working example.


有一段时间我为自己写了一个小脚本,called js.colorGradient。它计算 0%100% 范围内的颜色。它甚至允许您使用两种以上的颜色来包装范围。它可能不是您要找的,但您可以随意更改它。

var gradient = new ColorGradient(["#FF0CB6", "#EC9CF4", "#0F0", "#00F"]);

for( var i = 0; i <= 100; i++ ) {
    var color = gradient.getHexColorAtPercent(i);
    $("#demo").append('<div style="background: ' + color + '">');
}

Working example.