Skip to content

Instantly share code, notes, and snippets.

@mhgbrown
Created March 21, 2016 16:30
Show Gist options
  • Save mhgbrown/51888b8d12e70ebfc4a3 to your computer and use it in GitHub Desktop.
Save mhgbrown/51888b8d12e70ebfc4a3 to your computer and use it in GitHub Desktop.
Create a favicon on page load based on the CSS color of the first few matching elements
/**
* Create a FAVICON_DIMENSIONxFAVICON_DIMENSION PNG favicon based on the
* CSS color of the first NUM_COLORED elements with the class COLORED_CLASS.
* The favicon is generated with the pattern:
* color 1 | white
* color 2 | white
* color 3 | white
* etc...
*
*/
(function(window, document, undefined) {
var NUM_COLORS = 6;
var NUM_COLORED = NUM_COLORS/2;
var COLORED_CLASS = "conversation";
var FAVICON_DIMENSION = 64;
var FAVICON_COLOR_CHANGE_INTERVAL = 2;
var FAVICON_SECTION_WIDTH = FAVICON_DIMENSION/FAVICON_COLOR_CHANGE_INTERVAL;
var FAVICON_SECTION_HEIGHT = FAVICON_DIMENSION/NUM_COLORED;
function setNewFavicon(imageData) {
var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.setAttribute('id', 'favicon');
newLink.rel = 'shortcut icon';
newLink.href = imageData;
docHead.appendChild(newLink);
}
function getFaviconImageData(fourColors) {
if(fourColors.length !== NUM_COLORS) {
console.warn('Tried to draw favicon with not NUM_COLORS colors');
return;
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.height = FAVICON_DIMENSION;
canvas.width = FAVICON_DIMENSION;
fourColors.forEach(function(color, index) {
ctx.beginPath();
ctx.rect(FAVICON_SECTION_WIDTH * ( index % FAVICON_COLOR_CHANGE_INTERVAL ), FAVICON_SECTION_HEIGHT * Math.floor( index / FAVICON_COLOR_CHANGE_INTERVAL ), FAVICON_SECTION_WIDTH, FAVICON_SECTION_HEIGHT);
ctx.fillStyle = color;
ctx.fill();
});
return canvas.toDataURL("image/png");
}
function getColors() {
var elements = document.getElementsByClassName(COLORED_CLASS);
var fristColors = Array.prototype.slice.apply(elements, [0, NUM_COLORED]).map(function(element) {
return element.style.color;
});
var i = NUM_COLORS;
while(i--) {
var current = NUM_COLORS - i;
if(current % 2 !== 0) {
fristColors.splice(current, 0, 'rgb(255, 255, 255)');
}
}
return fristColors;
}
window.addEventListener('load', function() {
var colors = getColors();
var imageData = getFaviconImageData(colors);
setNewFavicon(imageData);
});
}(window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment