identicon.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * Identicon.js v1.0
  3. * http://github.com/stewartlord/identicon.js
  4. *
  5. * Requires PNGLib
  6. * http://www.xarg.org/download/pnglib.js
  7. *
  8. * Copyright 2013, Stewart Lord
  9. * Released under the BSD license
  10. * http://www.opensource.org/licenses/bsd-license.php
  11. */
  12. (function() {
  13. Identicon = function(hash, size, margin){
  14. this.hash = hash;
  15. this.size = size || 64;
  16. this.margin = margin || .08;
  17. }
  18. Identicon.prototype = {
  19. hash: null,
  20. size: null,
  21. margin: null,
  22. render: function(){
  23. var hash = this.hash,
  24. size = this.size,
  25. margin = Math.floor(size * this.margin),
  26. cell = Math.floor((size - (margin * 2)) / 5),
  27. image = new PNGlib(size, size, 256);
  28. // light-grey background
  29. var bg = image.color(240, 240, 240);
  30. // foreground is last 7 chars as hue at 50% saturation, 70% brightness
  31. var rgb = this.hsl2rgb(parseInt(hash.substr(-7), 16) / 0xfffffff, .5, .7),
  32. fg = image.color(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255);
  33. // the first 15 characters of the hash control the pixels (even/odd)
  34. // they are drawn down the middle first, then mirrored outwards
  35. var i, color;
  36. for (i = 0; i < 15; i++) {
  37. color = parseInt(hash.charAt(i), 16) % 2 ? bg : fg;
  38. if (i < 5) {
  39. this.rectangle(2 * cell + margin, i * cell + margin, cell, cell, color, image);
  40. } else if (i < 10) {
  41. this.rectangle(1 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
  42. this.rectangle(3 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);
  43. } else if (i < 15) {
  44. this.rectangle(0 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
  45. this.rectangle(4 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);
  46. }
  47. }
  48. return image;
  49. },
  50. rectangle: function(x, y, w, h, color, image) {
  51. var i, j;
  52. for (i = x; i < x + w; i++) {
  53. for (j = y; j < y + h; j++) {
  54. image.buffer[image.index(i, j)] = color;
  55. }
  56. }
  57. },
  58. // adapted from: https://gist.github.com/aemkei/1325937
  59. hsl2rgb: function(h, s, b){
  60. h *= 6;
  61. s = [
  62. b += s *= b < .5 ? b : 1 - b,
  63. b - h % 1 * s * 2,
  64. b -= s *= 2,
  65. b,
  66. b + h % 1 * s,
  67. b + s
  68. ];
  69. return[
  70. s[ ~~h % 6 ], // red
  71. s[ (h|16) % 6 ], // green
  72. s[ (h|8) % 6 ] // blue
  73. ];
  74. },
  75. toString: function(){
  76. return this.render().getBase64();
  77. }
  78. }
  79. window.Identicon = Identicon;
  80. })();