Skip to content

Instantly share code, notes, and snippets.

@SaurusAraAra
Created May 19, 2026 18:23
Show Gist options
  • Select an option

  • Save SaurusAraAra/618e2cf9d7e069fcf253141a7527f6cc to your computer and use it in GitHub Desktop.

Select an option

Save SaurusAraAra/618e2cf9d7e069fcf253141a7527f6cc to your computer and use it in GitHub Desktop.
const { createCanvas, GlobalFonts } = require("@napi-rs/canvas")
const axios = require("axios")
const fs = require("fs")
const path = require("path")
const os = require("os")
const font_url =
"https://raw.githubusercontent.com/saurusrawr/penting/main/font/ARIALN.ttf"
const font_cache = path.join(os.tmpdir(), "arialn.ttf")
let font_ready = false
async function loadFont() {
if (font_ready) return
if (!fs.existsSync(font_cache)) {
const { data } = await axios.get(font_url, {
responseType: "arraybuffer",
timeout: 15000
})
fs.writeFileSync(font_cache, Buffer.from(data))
}
GlobalFonts.registerFromPath(font_cache, "ArialNarrow")
font_ready = true
}
function smartChunk(str) {
const words = str.split(" ")
const lines = []
let i = 0
while (i < words.length) {
const remaining = words.slice(i)
const next = remaining.slice(0, 3)
const avg = next.reduce((a, w) => a + w.length, 0) / next.length
const count = Math.min(avg > 5 ? 2 : 3, remaining.length)
lines.push(remaining.slice(0, count).join(" "))
i += count
}
return lines
}
function getStartSize(len) {
if (len <= 1) return 600
if (len <= 2) return 500
if (len <= 3) return 420
if (len <= 5) return 340
return 260
}
async function makeBrat(text) {
await loadFont()
const size = 1000
const padding = 80
const gap = 20
const maxWidth = size - padding * 2
const lines = smartChunk(text)
let fontSize = getStartSize(lines.length)
const canvas = createCanvas(size, size)
const ctx = canvas.getContext("2d")
while (fontSize > 10) {
ctx.font = `${fontSize}px ArialNarrow`
const fit = lines.every(
(l) => ctx.measureText(l).width <= maxWidth
)
if (fit) break
fontSize -= 2
}
ctx.fillStyle = "#FFFFFF"
ctx.fillRect(0, 0, size, size)
ctx.fillStyle = "#000000"
ctx.font = `${fontSize}px ArialNarrow`
ctx.textAlign = "left"
ctx.textBaseline = "top"
let y = padding
for (const line of lines) {
ctx.fillText(line, padding, y)
y += fontSize + gap
}
return canvas.encode("png")
}
async function bratHandler(req, res) {
const text = "saurus ku gacor"
try {
const img = await makeBrat(text)
res.setHeader("Content-Type", "image/png")
res.send(img)
} catch (e) {
res.status(500).json({
status: false,
message: e.message
})
}
}
module.exports = bratHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment