-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
91 lines (75 loc) · 2.04 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const { createCanvas } = require('canvas')
const fs = require('fs')
/**
* Transforms R, G and B into a hex color string.
* @param r
* @param g
* @param b
* @returns {string}
*/
const colorToHex = (r, g, b) => '#' +
(r.toString(16).padStart(2, '0')) +
(g.toString(16).padStart(2, '0')) +
(b.toString(16).padStart(2, '0'))
/**
* Inverts a color and returns its hex value
* @param r
* @param g
* @param b
* @returns {string}
*/
const invertColor = (r, g, b) => colorToHex(
(255 - r),
(255 - g),
(255 - b)
)
/**
* Generates an image with a given set of options
* @param userOptions
*/
const generateImage = userOptions => {
const defaultOptions = {
width: 640,
height: 480,
r: 255,
g: 255,
b: 255,
text: 'Lorem ipsum',
font: 'san-serif',
output: './image.png'
}
const options = {
...defaultOptions,
...userOptions
}
let type = options.output.split('.').pop()
if (type === 'jpeg') {
type = 'jpg'
}
const allowedTypes = ['png', 'jpg', 'pdf', 'svg']
if (allowedTypes.indexOf(type) === -1) {
throw new Error(`Unknown image type "${type}", expected one of "${allowedTypes.join('", "')}"`)
}
const width = options.width
const height = options.height
const color = colorToHex(options.red, options.green, options.blue)
const textColor = invertColor(options.red, options.green, options.blue)
const canvas = createCanvas(width, height, type)
const context = canvas.getContext('2d')
const fontSize = height / 10
context.fillStyle = color
context.fillRect(0, 0, width, height)
context.fillStyle = textColor
context.font = `${fontSize}px ${options.font}`
const textSize = context.measureText(options.text)
context.fillText(options.text , (canvas.width / 2) - (textSize.width / 2), (canvas.height / 2) + (fontSize / 2))
const mimeTypes = {
png: 'image/png',
jpg: 'image/jpeg',
pdf: 'application/pdf',
svg: 'image/svg+xml'
}
const buffer = canvas.toBuffer(mimeTypes[type])
fs.writeFileSync(options.output, buffer)
}
module.exports = generateImage