Smashed Blog Development

Tag Archive: favicon

Recreating the Gmail dynamic favicon with canvas

Comments Off

I’m currently using this for a web application I’m working on. Pass an integer to it and you’re set.

View Demo

function updateFavicon(i) {
	var canvas = document.createElement('canvas'),
	ctx,
	img = document.createElement('img'),
	link = document.getElementById('favicon').cloneNode(true)//,
		
	if (canvas.getContext) {
		canvas.height = canvas.width = 16; // set the size
		ctx = canvas.getContext('2d');
		img.onload = function () { // once the image has loaded
			ctx.drawImage(this, 0, 0);
			y = "15";
			if (i <= 9) { //moves x coordinates depending on value
				x = "9";
			} else if (i > 9 && i < 99) {
				x = "5";
			} else if (i > 99 && i < 999) {
				x = "1";
			} else if (i > 999) { //doesn't display >999
				x = "0";
				i = "";
			}

			ctx.font = '9px sans-serif';
			ctx.lineWidth = 3;
			ctx.strokeStyle = "#fff";
			ctx.strokeText(i, x, y);
			ctx.fillStyle = '#111';
			ctx.fillText(i, x, y);

			link.href = canvas.toDataURL('image/png');
			document.body.appendChild(link);
		};
		img.src = 'favicon.png'; //path to favicon
	}
};