dtao / nearest-color

Find the nearest color
danieltao.com/nearest-color
MIT License
346 stars 31 forks source link

Detecting depends on 'from' colors ordering? #4

Closed indapublic closed 7 years ago

indapublic commented 7 years ago
const dominantColor = '#6C36AC'
console.info(dominantColor)
const nearestColor = NearestColor.from(['#f5fffa', '#a020f0', '#808080',])(dominantColor)
console.info(nearestColor)  //  Outputs #a020f0
const nearestColor2 = NearestColor.from(['#f5fffa', '#808080', '#a020f0'])(dominantColor)
console.info(nearestColor2) //  Outputs #808080

What expected: '#a020f0' in both cases

dtao commented 7 years ago

Well, this is certainly an edge case. The issue here is that the two colors #a020f0 and #808080 are actually equidistant from #6C36AC.

The RGB value for #a020f0 is: { r: 160, g: 32, b: 240 }

The RGB value for #808080 is: { r: 128, g: 128, b: 128 }

The RGB value for #6C36AC is: { r: 108, g: 54, b: 172 }

So the distance from #6C36AC to #a020f0 is sqrt((160 - 108)^2 + (32 - 54)^2 + (240 - 172)^2) = sqrt(7812) = 88.38551917593742. The distance from #808080 to #6C36AC is sqrt((128 - 108)^2 + (128 - 54)^2 + (128 - 172)^2) = sqrt(7812) = 88.38551917593742.

In this scenario, when two colors in the list are the same distance from the specified color, then yes, ordering matters: the first one wins out.

Hope that helps!

indapublic commented 7 years ago

Thanks for reply @dtao. Maybe you know some better algorithm for similar color searching?