Skip to content

Instantly share code, notes, and snippets.

@sn3p
Created February 8, 2017 17:24
Show Gist options
  • Save sn3p/c24fb054f57f13c8846d3c045432500a to your computer and use it in GitHub Desktop.
Save sn3p/c24fb054f57f13c8846d3c045432500a to your computer and use it in GitHub Desktop.
Dynamic favicon with count badge
// Usage:
// <link rel="shortcut icon" href="favicon.png" data-count"5">
(() => {
const faviconSize = 32;
const favicon = document.querySelector('[data-count]')
// No notifications
if (!favicon || !favicon.dataset.count) {
return;
}
const count = parseFloat(favicon.dataset.count);
const countText = (count > 9 ? '9+' : '' + count);
const canvas = document.createElement('canvas');
const img = document.createElement('img');
if (canvas.getContext) {
canvas.height = canvas.width = faviconSize;
const ctx = canvas.getContext('2d');
img.onload = () => {
ctx.drawImage(img, 0, 0);
// Draw rect
const rectHeight = faviconSize * 0.8;
const rectWidth = rectHeight * (count > 9 ? 1.1 : 0.8);
const rectX = faviconSize - rectWidth;
const rectY = faviconSize - rectHeight;
const cornerRadius = faviconSize / 3;
ctx.lineJoin = 'round';
ctx.lineWidth = cornerRadius;
ctx.strokeStyle = ctx.fillStyle = '#ea6c6c';
ctx.strokeRect(
rectX + (cornerRadius / 2),
rectY + (cornerRadius / 2),
rectWidth - cornerRadius,
rectHeight - cornerRadius
);
ctx.fillRect(
rectX + (cornerRadius / 2),
rectY + (cornerRadius / 2),
rectWidth - cornerRadius,
rectHeight - cornerRadius
);
// Draw number
const textSize = rectHeight * 0.85;
const textX = rectX + rectWidth / 2;
const textY = rectY + rectHeight - textSize / 4;
ctx.font = `bold ${textSize}px helvetica, sans-serif`;
ctx.textAlign = 'center';
ctx.fillStyle = '#ffffff';
ctx.fillText(countText, textX, textY);
// Replace favicon
favicon.href = canvas.toDataURL('image/png');
};
img.src = favicon.href;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment