-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (61 loc) · 1.89 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
let port = process.env.PORT || 3000;
server.listen(port);
console.log('Server started! It\'s listening on port %s', port);
function createSvgXml({width = 100, height = 100, bgColor = '#999', fColor = '#fff', text = undefined}){
if(text){
return `
<svg xmlns="http://www.w3.org/2000/svg" height="${height}" width="${width}">
<rect width="${width}" height="${height}" style="fill:${bgColor}" />
<text x="50%" y="50%" font-size="20" dy=".3em" fill="${fColor}" text-anchor="middle">${text}</text>
</svg>
`;
}else{
return `
<svg xmlns="http://www.w3.org/2000/svg" height="${height}" width="${width}">
<rect width="${width}" height="${height}" style="fill:${bgColor}" />
<text x="50%" y="50%" font-size="20" dy=".3em" fill="${fColor}" text-anchor="middle">${width}x${height}</text>
</svg>
`;
}
}
app.get('/', function(req, res){
res.send('Welcome to image-holder...');
});
app.get('/:widthHeight', function(req, res, next){
let width = req.params.widthHeight.split('x')[0];
let height = req.params.widthHeight.split('x')[1];
if(width && height){
var svgXml = createSvgXml({
width: width,
height: height
});
res.type('image/svg+xml');
res.send(svgXml);
res.end();
}else{
next();
}
});
app.get('/:widthHeight/:bgColor/:fColor', function(req, res){
let width = req.params.widthHeight.split('x')[0];
let height = req.params.widthHeight.split('x')[1];
let bgColor = req.params.bgColor;
let fColor = req.params.fColor;
let text = req.query.text;
let svgXml = createSvgXml({
width: width,
height: height,
bgColor: '#' + bgColor,
fColor: '#' + fColor,
text: text
});
res.type('image/svg+xml');
res.send(svgXml);
res.end();
});
app.use((req, res) => {res.send('参数错误,请检查参数后重试...');});