Kennis Blogs HTML5 canvas in the browser and on the server

HTML5 canvas in the browser and on the server

HTML 5 Canvas in the browser and on the server

For our upcoming event Asas 2014 we are currently working on a custom ticketing system. One of the requirements we got from our UX designer is that it should be possible to preview the ticket you will get on Asas 2014. And ideally we should be able to print an exact copy of the preview.

Our first idea was to render an image on the server and keep refreshing from the server. But then we stumbled upon the library node-canvas this is a Cairo backed canvas implementation. This would make it possible to render the preview with HTML5 and then render the ticket on the server to a PNG, JPEG or a PDF. Here is a little sneak preview:

 

6MBEv9yA4f

 

The only difference between the server and browser version is the instantiation of the canvas element.

 

On the server you need to import the node canvas library and create a canvas instance as follows

 

var Canvas = require('canvas');
var canvas = new Canvas(400, 300)

 

On the client you add a canvas element to the dom:

<canvas width="400" height="300" id="canvasElement" />

 

And then retrieve it from the dom

var canvas = document.getElementById("canvasElement");

 

Here comes the cool stuff the following code runs on the server and client

var ctx = canvas.getContext('2d');
ctx.font = "30pt Arial";
ctx.textAlign="left";
ctx.fillStyle = "#2c97dd";
ctx.fillText("ASAS 2014", 85, 85);
ctx.save();

This should give you something like this: Screenshot 2014-03-11 17.38.17

Happy hacking!