-
Notifications
You must be signed in to change notification settings - Fork 8
/
favcount.js
102 lines (85 loc) · 2.67 KB
/
favcount.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* favcount.js v1.5.0
* http://chrishunt.co/favcount
* Dynamically updates the favicon with a number.
*
* Copyright 2013, Chris Hunt
* Released under the MIT license
*/
(function(){
function Favcount(icon) {
this.icon = icon;
this.opacity = 0.4;
this.canvas = document.createElement('canvas');
this.font = "Helvetica, Arial, sans-serif";
}
Favcount.prototype.set = function(count) {
var self = this,
img = document.createElement('img');
if (self.canvas.getContext) {
img.crossOrigin = "anonymous";
img.onload = function() {
drawCanvas(self.canvas, self.opacity, self.font, img, normalize(count));
};
img.src = this.icon;
}
};
function normalize(count) {
count = Math.round(count);
if (isNaN(count) || count < 1) {
return '';
} else if (count < 10) {
return ' ' + count;
} else if (count > 99) {
return '99';
} else {
return count;
}
}
function drawCanvas(canvas, opacity, font, img, count) {
var head = document.getElementsByTagName('head')[0],
favicon = document.querySelector('link[rel=icon]'),
newFavicon = document.createElement('link'),
multiplier, fontSize, context, xOffset, yOffset, border, shadow;
// Scale canvas elements based on favicon size
multiplier = img.width / 16;
fontSize = multiplier * 11;
xOffset = multiplier;
yOffset = multiplier * 11;
border = multiplier;
shadow = multiplier * 2;
canvas.height = canvas.width = img.width;
context = canvas.getContext('2d');
context.font = 'bold ' + fontSize + 'px ' + font;
// Draw faded favicon background
if (count) { context.globalAlpha = opacity; }
context.drawImage(img, 0, 0);
context.globalAlpha = 1.0;
// Draw white drop shadow
context.shadowColor = '#FFF';
context.shadowBlur = shadow;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
// Draw white border
context.fillStyle = '#FFF';
context.fillText(count, xOffset, yOffset);
context.fillText(count, xOffset + border, yOffset);
context.fillText(count, xOffset, yOffset + border);
context.fillText(count, xOffset + border, yOffset + border);
// Draw black count
context.fillStyle = '#000';
context.fillText(count,
xOffset + (border / 2.0),
yOffset + (border / 2.0)
);
// Replace favicon with new favicon
newFavicon.rel = 'icon';
newFavicon.href = canvas.toDataURL('image/png');
if (favicon) { head.removeChild(favicon); }
head.appendChild(newFavicon);
}
this.Favcount = Favcount;
}).call(this);
(function(){
Favcount.VERSION = '1.5.1';
}).call(this);