how to get rgb values for a color that's close to another color?

后端 未结 2 795
梦如初夏
梦如初夏 2021-01-16 00:33

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?

2条回答
  •  孤街浪徒
    2021-01-16 00:45

    It all depends what means 'close' to you. You can make function like:

    var color1 = { "r": 255, "g": 255, "b": 255 }
    var color2 = { "r": 250, "g": 252, "b": 252 }
    
    function isClose(color1, color2) {
        var threshold = 30;
        var distance = Math.abs(color1.r - color2.r) + Math.abs(color1.g - color2.g) + Math.abs(color1.b - color2.b);
    
        if (distance < threshold) return true;
        return false;
    }
    

    which would match colors that are very close (based on simple rgb vector distance), but still there is a threshold parameter which has to be chosen experimentally.

提交回复
热议问题