|
| 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 | +} |
0 commit comments