Skip to content

Commit eaddc60

Browse files
committed
LunaticHacker|Unique-Avatar-Generator/| Added an Express api that returns a unique avatar from username
1 parent 25c0b9b commit eaddc60

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

Unique-Avatar-Generator/app.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
const { createCanvas } = require("canvas");
2+
const MD5 = require("crypto-js/md5");
3+
const express = require("express");
4+
const app = express();
5+
const port = process.env.PORT || "8000";
6+
app.use(express.static("client"));
7+
8+
app.get("/api/:name", (req, res) => {
9+
image = generate(req.params.name);
10+
res.json({ img: image });
11+
});
12+
13+
app.listen(port);
14+
15+
function generate(name) {
16+
const canvas = createCanvas(200, 200);
17+
const ctx = canvas.getContext("2d");
18+
let hash = MD5(name).toString();
19+
let props = {};
20+
props.bgcolor = hash.substring(0, 4);
21+
props.facecolor = hash.substring(4, 8);
22+
props.eyecolor = hash.substring(8, 12);
23+
props.mouthcolor = hash.substring(12, 16);
24+
props.lefteyesize = map(
25+
parseInt(hash.substring(16, 20), 16) % 50,
26+
0,
27+
50,
28+
10,
29+
50
30+
);
31+
props.righteyesize = map(
32+
parseInt(hash.substring(20, 24), 16) % 50,
33+
0,
34+
50,
35+
10,
36+
50
37+
);
38+
props.mouthsize = map(
39+
parseInt(hash.substring(24, 28), 16) % 50,
40+
0,
41+
50,
42+
10,
43+
30
44+
);
45+
ctx.fillStyle = `#${props.bgcolor}`;
46+
ctx.fillRect(0, 0, 200, 200);
47+
ctx.translate(100, 100);
48+
ctx.strokeStyle = "#000000";
49+
ctx.fillStyle = `#${props.facecolor}`;
50+
ctx.beginPath();
51+
ctx.arc(0, 0, 50, 0, 2 * Math.PI);
52+
ctx.stroke();
53+
ctx.fill();
54+
ctx.fillStyle = `#${props.eyecolor}`;
55+
ctx.beginPath();
56+
ctx.arc(-20, 0, props.lefteyesize / 2, 0, 2 * Math.PI);
57+
ctx.fill();
58+
ctx.stroke();
59+
ctx.beginPath();
60+
ctx.arc(20, 0, props.righteyesize / 2, 0, 2 * Math.PI);
61+
ctx.fill();
62+
ctx.stroke();
63+
ctx.fillStyle = `#${props.mouthcolor}`;
64+
ctx.beginPath();
65+
ctx.arc(0, 30, props.mouthsize / 2, 0, 2 * Math.PI);
66+
ctx.fill();
67+
ctx.stroke();
68+
69+
return canvas.toDataURL();
70+
}
71+
function map(n, start1, stop1, start2, stop2) {
72+
const newval = ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2;
73+
return newval;
74+
}

Unique-Avatar-Generator/package.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"name": "avatar-maker",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "app.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1",
8+
"start": "node app.js"
9+
},
10+
"keywords": [],
11+
"author": "",
12+
"license": "ISC",
13+
"dependencies": {
14+
"canvas": "^2.6.1",
15+
"crypto-js": "^4.0.0",
16+
"express": "^4.17.1"
17+
}
18+
}

0 commit comments

Comments
 (0)