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?
- Does this have to do with Canvas/user input? And are you using jQuery?Fabrício Matté– Fabrício Matté2012-07-16 14:22:11 +00:00Commented Jul 16, 2012 at 14:22
- Could you give an example of a color which would be close to another and one which would not be close to it?smilly92– smilly922012-07-16 14:23:02 +00:00Commented Jul 16, 2012 at 14:23
- 1It all depends on how you define 'close'. Do you mean close in hue? Close in luminosity?robertc– robertc2012-07-16 14:48:47 +00:00Commented Jul 16, 2012 at 14:48
Add a comment |
2 Answers
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 ||
Comments
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.
1 Comment
andAnother1
wouldnt threshold be higher than 255 then? In Photoshop for example the maximum tolerance is 255, yours would be 765