In the last post, I wrote a simple example to be able to generate SVGs through RaphaelJS on the server.
Now I would like to showcase how to accomplish a similar task – generating badges – again with a simple NodeJS server.
The approach
Shields are made of 3 main parts, a text on the left, a text on the right and the background color of the latter.
That said, it’s pretty clear we will want to receive those parameters in the HTTP request to the server and generate an SVG accordingly: we will simply use a base template and generate the image on the fly.
For the templating part we will use swig, and to simplify the process of extracting request parameters we will simply rely on the evergreen express.
Show me the code!
First, let’s create a package json so that we can
npm install
the required dependencies:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Now, down to the “real” code : let’s start by simply creating a
brand new express app that receives requests at
/badge/:left/:right/:color
and renders an SVG
template:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
At this point, we will need to create the SVG template, and we will take inspiration from shields.io’s one, which is quite battle-tested:
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 |
|
At this point we’re set; we can just run node index.js
and
hit localhost:3000/my%20 badge/is%20great/green
to see
the generated badge appear:
MOAR!
Keeping in mind that you have to URLescape special characters, you can now play around with many different combinations:
http://localhost:3000/badge/code/bad/red
is a very simple badgehttp://localhost:3000/badge/code/bad/%23cc0033
shows that you can also specify colors in the traditional hex notation
and so on and so fort: you can definitely feel free to customize the code to add some more variables, tweak the template and make small adjustments.
All in all, now I guess you see how these shields are generated :)
For the lazy ones…
Since I wanted to have a working example that people could run, rather than simply copypasting code from this post around, I created a simple github repo for nodejs-badges so that you can play around with more ease.