Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active February 8, 2017 15:37
Show Gist options
  • Save bellbind/b528e26a63c8db919e0d to your computer and use it in GitHub Desktop.
Save bellbind/b528e26a63c8db919e0d to your computer and use it in GitHub Desktop.
[browser][WebCrypto] Identicon generator with WebCrypto API
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Simple Identicon Generator</title>
<script src="script.js"></script>
</head>
<body>
Type Your ID: <input id="id" />
<div>
<canvas id="icon" width="420" height="420"
style="background-color: #f0f0f0;"/>
</div>
</body>
</html>
"use strict";
window.addEventListener("load", ev => {
const id = document.getElementById("id");
const icon = document.getElementById("icon");
const c2d = icon.getContext("2d");
function drawIcon(ev) {
const buf = new TextEncoder("utf-8").encode(id.value.trim());
crypto.subtle.digest({name: "SHA-1"}, buf).then(hashToIcon).then(draw);
}
function hashToIcon(hash) {
const dv = new DataView(hash);
const hue = dv.getUint16(0, true) % 360;
const sat = dv.getUint8(2) % 50 + 25;
const lum = dv.getUint8(3) % 50 + 25;
const buf = Array.from(new Uint8Array(hash, 4, 15));
const col5x3 = split(buf.map(v => v % 2 === 1), 5);
const cols = col5x3.concat([col5x3[1], col5x3[0]]);
return {hue, sat, lum, cols};
}
function split(a, n) {
return Array.from(Array(Math.ceil(a.length / n)),
(_, i) => a.slice(i * n, i * n + n));
}
function draw(icon) {
const {width, height} = c2d.canvas;
const block = {w: width / 6, h: height / 6};
const pad = {w: block.w / 2, h: block.h / 2};
c2d.fillStyle = c2d.canvas.style.backgroundColor;
c2d.fillRect(0, 0, width, height);
c2d.fillStyle = `hsl(${icon.hue}, ${icon.sat}%, ${icon.lum}%)`;
icon.cols.forEach((col, x) => col.forEach((cell, y) => {
if (cell) c2d.fillRect(
pad.w + x * block.w, pad.h + y * block.h, block.w, block.h);
}));
}
id.addEventListener("input", drawIcon, false);
}, false);
@bellbind
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment