Skip to content

Instantly share code, notes, and snippets.

@goto-bus-stop
Created August 27, 2015 15:41
Show Gist options
  • Save goto-bus-stop/315d94735ea05b7a0675 to your computer and use it in GitHub Desktop.
Save goto-bus-stop/315d94735ea05b7a0675 to your computer and use it in GitHub Desktop.
fake plug.dj ban image generator
var Canvas = require('canvas')
var http = require('http')
var PORT = 8088
// stolen from http://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ')
var line = ''
var wrapped = false
for(var i = 0; i < words.length; i++) {
var testLine = line + words[i] + ' '
var metrics = context.measureText(testLine)
var testWidth = metrics.width
if (testWidth > maxWidth && i > 0) {
context.fillText(line, x, y)
line = words[i] + ' '
y += lineHeight
wrapped = true
}
else {
line = testLine
}
}
context.fillText(line, x, y)
return wrapped
}
http.createServer(function (req, res) {
var canvas = new Canvas(281, 32)
var context = canvas.getContext('2d')
var name = decodeURIComponent(req.url)
.replace(/^\/@?|\.png(?:\?.*)?$/g, '')
.replace(/&gt;/g, '>')
.replace(/&lt;/g, '<')
.replace(/&amp;/g, '&')
.replace(/&#39;/g, '\'')
.replace(/&#34;/g, '"')
var text = 'permanently banned ' + name + ' from the community.'
context.fillStyle = '#a670fe'
context.font = '500 12px Roboto'
if (!wrapText(context, text, 0, 14, 281, 16)) {
var newCanvas = new Canvas(281, 16)
var newContext = newCanvas.getContext('2d')
newContext.drawImage(canvas, 0, 0)
canvas = newCanvas
}
res.writeHead(200, { 'content-type': 'image/png' })
canvas.pngStream().pipe(res)
}).listen(PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment