Created
January 16, 2019 13:36
-
-
Save razdvapoka/2dfdde2ad061110c53052cf2686a02f1 to your computer and use it in GitHub Desktop.
draw image with node-canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { | |
createCanvas, | |
registerFont, | |
loadImage | |
} = require('canvas') | |
// подгружаем шрифт | |
registerFont('./static/fonts/d-m.woff', { family: 'D-M' }) | |
// рисуем картинку | |
const drawResultImage = async (prediction, lng, emoji) => { | |
const canvas = createCanvas(1200, 630) | |
const ctx = canvas.getContext('2d') | |
const image = prediction <= 0 | |
? lng === 'ru' ? resultTemplateFail : resultTemplateFailEn | |
: lng === 'ru' ? resultTemplate : resultTemplateEn | |
ctx.drawImage(image, 0, 0) | |
ctx.font = '100px D-M' | |
const { width: textWidth } = ctx.measureText(`$${prediction}`) | |
const textX = 600 - (textWidth + 120 + 20) / 2 | |
ctx.fillText(`$${prediction}`, textX, 450) | |
if (emojis[emoji]) { | |
ctx.drawImage(emojis[emoji], textX + textWidth + 20, 350, 120, 120) | |
} | |
return canvas | |
} | |
// ручка для получения картинки | |
server.get('/result-image/:data', async (req, res) => { | |
try { | |
const jsonString = cryptr.decrypt(req.params.data) | |
const result = JSON.parse(jsonString) | |
const status = getStatus(result.prediction) | |
res.setHeader('Content-Type', 'image/png') | |
const image = await drawResultImage(result.prediction, result.lng, status.emoji) | |
image.pngStream().pipe(res) | |
} catch (e) { | |
console.log(e) | |
res.end('smth went wrong', e) | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment