forked from OpenBazaar/OpenBazaar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identicon.js
92 lines (80 loc) · 2.99 KB
/
identicon.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
/**
* Identicon.js v1.0
* http://github.com/stewartlord/identicon.js
*
* Requires PNGLib
* http://www.xarg.org/download/pnglib.js
*
* Copyright 2013, Stewart Lord
* Released under the BSD license
* http://www.opensource.org/licenses/bsd-license.php
*/
(function() {
Identicon = function(hash, size, margin){
this.hash = hash;
this.size = size || 64;
this.margin = margin || .08;
}
Identicon.prototype = {
hash: null,
size: null,
margin: null,
render: function(){
var hash = this.hash,
size = this.size,
margin = Math.floor(size * this.margin),
cell = Math.floor((size - (margin * 2)) / 5),
image = new PNGlib(size, size, 256);
// light-grey background
var bg = image.color(240, 240, 240, 0);
// foreground is last 7 chars as hue at 50% saturation, 70% brightness
var rgb = this.hsl2rgb(parseInt(hash.substr(-7), 16) / 0xfffffff, .5, .7),
fg = image.color(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255);
// the first 15 characters of the hash control the pixels (even/odd)
// they are drawn down the middle first, then mirrored outwards
var i, color;
for (i = 0; i < 15; i++) {
color = parseInt(hash.charAt(i), 16) % 2 ? bg : fg;
if (i < 5) {
this.rectangle(2 * cell + margin, i * cell + margin, cell, cell, color, image);
} else if (i < 10) {
this.rectangle(1 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
this.rectangle(3 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
} else if (i < 15) {
this.rectangle(0 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
this.rectangle(4 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
}
}
return image;
},
rectangle: function(x, y, w, h, color, image) {
var i, j;
for (i = x; i < x + w; i++) {
for (j = y; j < y + h; j++) {
image.buffer[image.index(i, j)] = color;
}
}
},
// adapted from: https://gist.github.com/aemkei/1325937
hsl2rgb: function(h, s, b){
h *= 6;
s = [
b += s *= b < .5 ? b : 1 - b,
b - h % 1 * s * 2,
b -= s *= 2,
b,
b + h % 1 * s,
b + s
];
return[
s[ ~~h % 6 ], // red
s[ (h|16) % 6 ], // green
s[ (h|8) % 6 ] // blue
];
},
toString: function(){
return this.render().getBase64();
}
}
window.Identicon = Identicon;
})();