-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
image-caption-overlay.js
87 lines (73 loc) · 2.16 KB
/
image-caption-overlay.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
import { createWriteStream } from 'fs'
import pify from 'pify'
import imageSizeOf from 'image-size'
import { createCanvas, loadImage, Image } from 'canvas'
const imageSizeOfP = pify(imageSizeOf)
function createImageFromBuffer (buffer) {
const image = new Image()
image.src = buffer
return image
}
function createCaptionOverlay ({
text,
width,
height,
font = 'Arial',
fontSize = 48,
captionHeight = 120,
decorateCaptionTextFillStyle = null,
decorateCaptionFillStyle = null,
offsetX = 0,
offsetY = 0
}) {
const canvas = createCanvas(width, height)
const ctx = canvas.getContext('2d')
const createGradient = (first, second) => {
const grd = ctx.createLinearGradient(width, captionY, width, height)
grd.addColorStop(0, first)
grd.addColorStop(1, second)
return grd
}
// Hold computed caption position
const captionX = offsetX
const captionY = offsetY + height - captionHeight
const captionTextX = captionX + (width / 2)
const captionTextY = captionY + (captionHeight / 2)
// Fill caption rect
ctx.fillStyle = decorateCaptionFillStyle
? decorateCaptionFillStyle(ctx)
: createGradient('rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0.45)')
ctx.fillRect(captionX, captionY, width, captionHeight)
// Fill caption text
ctx.textBaseline = 'middle'
ctx.textAlign = 'center'
ctx.font = `${fontSize}px ${font}`
ctx.fillStyle = decorateCaptionTextFillStyle
? decorateCaptionTextFillStyle(ctx)
: 'white'
ctx.fillText(text, captionTextX, captionTextY)
return createImageFromBuffer(canvas.toBuffer())
}
(async () => {
try {
const source = 'images/lime-cat.jpg'
const { width, height } = await imageSizeOfP(source)
const canvas = createCanvas(width, height)
const ctx = canvas.getContext('2d')
// Draw base image
const image = await loadImage(source)
ctx.drawImage(image, 0, 0)
// Draw caption overlay
const overlay = await createCaptionOverlay({
text: 'Hello!',
width,
height
})
ctx.drawImage(overlay, 0, 0)
// Output to `.png` file
canvas.createPNGStream().pipe(createWriteStream('foo.png'))
} catch (err) {
console.log(err)
process.exit(1)
}
})()