Last active
August 29, 2015 14:09
-
-
Save CharlieHawker/d56ca040cf459d1733a5 to your computer and use it in GitHub Desktop.
Find the closest color match to a given hex/RGB color from a given palette
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Find the closest color match to a given hex/RGB color from a given palette */ | |
@function closest-color($color, $palette: ()) { | |
// break down into individual colors | |
$components: red($color), green($color), blue($color); | |
// set some matching vars | |
$diff: 765; // 255 * 3, maximum possible diff | |
$closest: false; // not set yet... | |
@each $palette-color in $palette { | |
$pdiffs: ( | |
(red($palette-color) - nth($components, 1)), | |
(green($palette-color) - nth($components, 2)), | |
(blue($palette-color) - nth($components, 3)) | |
); | |
$pdiff: 0; | |
@each $pd in $pdiffs { | |
@if ($pd < 0) { | |
$pdiff: $pdiff + (-1 * $pd); | |
} | |
@else { | |
$pdiff: $pdiff + $pd; | |
} | |
} | |
// see if we have a direct match? | |
@if $pdiff == 0 { | |
@return $palette-color; | |
} | |
// otherwise update diff & closest color vars if this is closer | |
@if $pdiff < $diff { | |
$diff: $pdiff; | |
$closest: $palette-color; | |
} | |
} | |
@if $closest { | |
@return $closest; | |
} | |
@else { | |
@error 'Unable to find a matching color'; // just in case | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment