Skip to content

Instantly share code, notes, and snippets.

@jeremypage
Last active June 29, 2017 15:22
Show Gist options
  • Save jeremypage/09ca5837d5175c359d818e7f0ca24097 to your computer and use it in GitHub Desktop.
Save jeremypage/09ca5837d5175c359d818e7f0ca24097 to your computer and use it in GitHub Desktop.
Use Vibrant.js to extract foreground and background colours from images (uses http://jariz.github.io/vibrant.js/)
(function ($) {
$(document).ready(function () {
$('.image-to-colour').each(function (index, element) {
var images = $(this).find('img');
if (images.length == 1) {
var imageColours = getImageColours(images[0]);
element.style.color = imageColours.textColour;
element.style.backgroundColor = imageColours.backgroundColour;
}
});
});
// Get suitable background and foreground colours from image
function getImageColours(image) {
var vibrant = new Vibrant(image);
var swatches = vibrant.swatches();
return {
backgroundColour: (swatches.LightMuted) ? swatches.LightMuted.getHex() : ((swatches.LightVibrant) ? swatches.LightVibrant.getHex() : '#fff'),
textColour: (swatches.LightMuted) ? swatches.LightMuted.getTitleTextColor() : ((swatches.LightVibrant) ? swatches.LightVibrant.getTitleTextColor() : '#000')
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment