Skip to content

Instantly share code, notes, and snippets.

@xorus
Created March 29, 2016 12:27
Show Gist options
  • Select an option

  • Save xorus/a4760ea103eb43e28093 to your computer and use it in GitHub Desktop.

Select an option

Save xorus/a4760ea103eb43e28093 to your computer and use it in GitHub Desktop.
Javascript : nearest material design color
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<input type="color" id="color">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinycolor/1.3.0/tinycolor.js"></script>
<script>
var colors = ['#000000','#E51C23','#E91E63','#9C07B0','#673AB7','#3F51B5','#5677FC','#03A9F4','#00BCD4','#009688',
'#259B24','#8BC34A','#CDDC39','#FFDB3B','#FFC107','#FF9800','#FFFFFF','#FF5722','#795548','#9E9E9E','#607D8B'];
var nearestInPalette = function (color, palette) {
var rgb = tinycolor(color).toRgb();
var minDist = 255*255*3;
var match = palette[0];
for (var i = 0; i < palette.length; i++) {
var palRgb = tinycolor(palette[i]).toRgb();
var dR = palRgb.r - rgb.r;
var dG = palRgb.g - rgb.g;
var dB = palRgb.b - rgb.b;
var dist = dR * dR + dG * dG + dB * dB;
if (dist < minDist) {
minDist = dist;
match = palette[i];
}
}
$("body").css('background-color', '#' + tinycolor(match).toHex())
};
$("#color").change(function () {
nearestInPalette($(this).val(), colors);
});
$("#color").on('input',function () {
nearestInPalette($(this).val(), colors);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment