forked from herber/gradient-avatar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
34 lines (29 loc) · 1.38 KB
/
index.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
const stringHash = require('string-hash');
const hslTriad = require('hsl-triad');
const hslRgb = require('hsl-rgb');
const uniqueID = () => Math.floor(Math.random() * Date.now());
const avatar = (str, size, shapeType) => {
const hash = stringHash(str);
const colors = hslTriad(hash % 360, 1, 0.5);
const color1 = hslRgb(colors[0][0], colors[0][1], colors[0][2]);
const color2 = hslRgb(colors[1][0], colors[1][1], colors[1][2]);
const color1str = `rgb(${ color1[0] }, ${ color1[1] }, ${ color1[2] })`;
const color2str = `rgb(${ color2[0] }, ${ color2[1] }, ${ color2[2] })`;
const id = uniqueID();
const shape = shapeType === 'circle' ?
`<circle id="Circle" fill="url(#${id})" cx="40" cy="40" r="40" />` :
`<rect id="Rectangle" fill="url(#${id})" x="0" y="0" width="80" height="80"></rect>`;
return `<?xml version="1.0" encoding="UTF-8"?>
<svg ${ size != undefined ? `width="${size}px" height="${size}px"` : '' } viewBox="0 0 80 80" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient x1="0%" y1="0%" x2="100%" y2="100%" id="${id}">
<stop stop-color="${color1str}" offset="0%"></stop>
<stop stop-color="${color2str}" offset="100%"></stop>
</linearGradient>
</defs>
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
${shape}
</g>
</svg>`;
};
module.exports = avatar;