Last active
July 11, 2019 08:43
-
-
Save hrsetyono/df1b85fd488be613f38ac38a890a9d96 to your computer and use it in GitHub Desktop.
JavaScript - Create one letter favicon dynamically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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' ); | |
} ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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