如何获取接近另一种颜色的颜色的rgb值?

问题描述:

如果我有一个RGB颜色。如何创建一个javascript函数,当另一个RGB值接近初始RGB时返回true,否则返回false?

If I have a color in RGB. How can I create a javascript function that returns true when another RGB value is close to the initial RGB and false otherwise?

I我用这个,它对我来说很好:

I've used this and it works very well for me:

// assuming that color1 and color2 are objects with r, g and b properties
// and tolerance is the "distance" of colors in range 0-255
function isNeighborColor(color1, color2, tolerance) {
    if(tolerance == undefined) {
        tolerance = 32;
    }

    return Math.abs(color1.r - color2.r) <= tolerance
        && Math.abs(color1.g - color2.g) <= tolerance
        && Math.abs(color1.b - color2.b) <= tolerance;
}

根据您的特定问题,颜色距离的含义可以不同,例如在您的情况下,您需要将&& 更改为 ||

and depending on your particular problem the meaning of the color distance can be different, for example maybe in your case you would need to change && to ||