Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Animated GIF based on multiple SVG frames (sharpjs) for Tydbit (in NodeJS)
import express from 'express'
import sharp from 'sharp'
import fetch from 'node-fetch'
import { Gif } from 'make-a-gif'
sharp.cache(false)
const app = express()
const port = 3000
const device = 'some-device-identifier-name-123'
const apikey = 'some.jwt.string'
const render = async res => {
const gif = new Gif(64, 32)
for await (const num of [1, 2, 3, 4, 5, 6]) {
const composites = []
const svg = `
<svg width="64" fill="orange" height="32" viewBox="0 0 64 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<filter id="crispify">
<feComponentTransfer>
<feFuncA type="discrete" tableValues="0 1"/>
</feComponentTransfer>
</filter>
</defs>
<rect stroke-width="0" fill="#${10-num}0${num}" x="0" y="0" width="64" height="32" rx="5"></rect>
<rect stroke-width="3" stroke="white" fill="purple" x="4" y="5" width="10" height="10" rx="5"></rect>
<text filter="url(#crispify)" text-anchor="middle" x="40" y="11" fill="white" style="font-family: JetBrains Mono; font-weight: 600; font-size: 10px">
${num}
</text>
<text filter="url(x#crispify)" text-anchor="middle" x="32" y="30" fill="white" style="font-family: Arial; font-weight: 400; font-size: 15px">
Hi you!
</text>
</svg>
`
composites.push({ input: Buffer.from(svg), top: 0, left: 0 })
const output =
await sharp({ create: { width: 64, height: 32, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 0 }, } })
.ensureAlpha().composite(composites).png().toBuffer()
await gif.addFrame({ src: new Uint8Array(output).buffer, duration: 500 })
}
const animated = await gif.encode()
const buf = Buffer.from(animated, 'binary')
res?.setHeader('Content-Type', 'image/gif')
await fetch('https://api.tidbyt.com/v0/devices/' + device, {
method: 'PATCH', headers: { 'Content-type': 'application/json', 'Authorization': 'Bearer ' + apikey },
body: JSON.stringify({ brightness: 20, autoDim: false, })
})
const f = await fetch('https://api.tidbyt.com/v0/devices/' + device + '/push', {
method: 'POST',
headers: { 'Content-type': 'application/json', 'Authorization': 'Bearer ' + apikey },
body: JSON.stringify({ image: animated.toString('base64'), background: false, installationID: 'nodejs', })
})
console.log('Rendered', await f.json())
return buf
}
// Render & serve on URL call
app.get('/', async (req, res) => {
res.send(Buffer.from(await render(res), 'binary'))
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// Render on app start
render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment