Skip to content

Instantly share code, notes, and snippets.

@hrsetyono
Last active July 11, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrsetyono/df1b85fd488be613f38ac38a890a9d96 to your computer and use it in GitHub Desktop.
Save hrsetyono/df1b85fd488be613f38ac38a890a9d96 to your computer and use it in GitHub Desktop.
JavaScript - Create one letter favicon dynamically
/**
* Automatically generate favicon using the first letter of a text
*/
function createFavicon( text, bgColor = '#004ea2', textColor = '#ffffff' ) {
var favicon = document.getElementById('favicon');
var faviconSize = 128;
var canvas = document.createElement( 'canvas' );
canvas.width = faviconSize;
canvas.height = faviconSize;
var context = canvas.getContext( '2d' );
var img = document.createElement( 'img' );
img.src = favicon.href;
img.onload = () => {
// Draw Original Favicon as Background
context.drawImage( img, 0, 0, faviconSize, faviconSize );
// Draw Notification Circle
context.beginPath();
context.rect( 0, 0, canvas.width, canvas.height );
// context.arc( canvas.width - faviconSize / 3 , faviconSize / 3, faviconSize / 3, 0, 2*Math.PI );
context.fillStyle = bgColor;
context.fill();
// Draw Notification Number
context.font = 'bold 110px "Roboto Condensed", sans-serif';
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = textColor;
var letter = text.substring( 0, 1 );
context.fillText( letter, canvas.width / 2, 75 );
// Replace favicon
favicon.href = canvas.toDataURL( 'image/png' );
};
}
// run
window.addEventListener( 'load', function() {
createFavicon( 'A', '#ff0000', '#ffffff' );
} );
<html>
<head>
...
<link id="favicon" rel="icon" href="transparent.png">
</head>
<body>
...
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment