Friday, June 28, 2013

Writing a real time single page application - client side

Introduction

In this two parts guide I will explain how to use backbone.js, node.js and socket.io (and many others libraries) to write a single page/real time application.
The guide's goal is to explain a system and I will not dive into details of every component, for this reason I suggest you to follow the links to get more informations.
The topic is quite hot, so let's get started !

First step: defining resources

This part is the most boring but it is very important.
In my application I should model every client server exchange using REST principles  (even though I will eventually use websockets instead of HTTP protocol).

Following these principles I need to define resources.
A resource is a well defined piece of information

Every resource should:
  • have an id (the URL)
  • be atomic (every exchange will be stateless)
A very important detail here is that resources don't need to match exactly with backend models (database schemas). For example a resource can be the result of a join between tables.

I will leave to node.js backend to manage the differences between the actual db models and resources.
The backend can update more than one model in a reliable way (and, in case, rolling back changes) while it's not so reliable do this directly from the client.

From this point when I talk about models in the client I am talking about an HTTP resources.

Client side

For the front end I will use backbone.js. This library's task is basically to organize homogeneous models (they are resources!) into collections and keep these data synchronized with the UI (view) and the backend.
This is a model:

var Item = Backbone.Model.extend({
    defaults: {
       "name": "",
       "description": "",
    },
    validate: function(attrs, options) {
        // return a string is attributes are wrong
    }
});

This is a simple collection:

var Items = Backbone.Collection.extend({
    model: Item,
    initialize: function (){
        //...
    }
});

This collection contains a group of Items.
A backbone collection usually has an url attribute that is used to download data from the server. So I'll rewrite the last collection:

var Items = Backbone.Collection.extend({
    url: "/items"
    model: Item,
    initialize: function (){
        //...
    }
});

Backbone.js uses AJAX by default to download and update collections. It uses the standard HTTP methods: GET POST PUT DELETE (optionally PATCH if supported).
If the collection's url is "/items" the single model urls will be "/items/model_id".

Backbone.IO

One of the nicest feature of Backbone.js is that you can use different ways to save your data (overwriting the Backbone.sync function).
In this example I will use backbone.io. This component sends data to the backend using a websocket or another available socket like transport (it uses socket.io under the hood).

Backbone.io.connect();

var Items = Backbone.Collection.extend({
    backend: 'items',
    model: Item,
    initialize: function (){
        this.bindBackend();        
        //...
    }
});

Backbone.io.connect is used to initialize websockets. I replaced the url attribute with a backend identifier.
I have also launched "bindBackend". This method connect backbone.io events to the collection events. So when the server broadcasts that something is changed the collection triggers the event and views are refreshed.

Views

Backbone.js main feature is to be unopinionated. Views, for example, are mostly boilerplate code. For this reason, you often need to build a more high level framework on top of it.
It is usually a good idea to use something like Marionette.
Anyway I tried to build something simpler. This is a model's view:

var ModelView = Backbone.View.extend({
    initialize: function (){
        this.initialEvents();
    },
    initialEvents: function (){
        if (this.model){
          this.listenTo(this.model, "change", this.render);
        }
    },
    serialize: function (){
        var attrs = _.clone(this.model.attributes);
        attrs.id = attrs[this.model.idAttribute];
        return attrs;
    },
    render: function (){
        this.preRender();
        this.$el.html(this.template(this.serialize()));
        this.postRender();
        return this;
    },
    preRender: function (){
        // this runs before the rendering
    },
    postRender: function (){
        // this runs after the rendering
    }
});

I also build a collection's view:

var CollectionView = Backbone.View.extend({
    contentSelector: '.append-item-here',
    // this is the class where I append the model views
    viewOptions: {},
    initialize: function (){
        this.children = {}; // this will contain the models views
        this.initialEvents();
    },
    initialEvents: function (){
        if (this.collection){
          this.listenTo(this.collection, "add", this.addChildView);
          this.listenTo(this.collection, "remove", this.removeChildView);
          this.listenTo(this.collection, "reset", this.render);
          this.listenTo(this.collection, "sort", this.render);
        }
    },   
    render: function (){
        var that = this;
        this.preRender();

        // I remove the old models views
        _.each(this.children, function (view){
            view.remove();
        });

        this.children = {};

        // I rebuild the models views
        this.collection.chain()
        .each(function(item, index){
            // every model view have a reference to its collection view
            var options = _.extend({index: index, parentView: that}, that.viewOptions);
            that.addChildView(item, that.collection, options);
        });

        this.postRender();
        return this;
    },
    // I can use this to filter some view if it is necessary
    filterView: function (model){
        return true;
    },
    addChildView: function (item, collection, options){
        // add a view to this.children trying to respect the sorting order
        var index;
        if (!this.filterView(item)){
            return;
        }
        options.model = item;
        if (options && options.index){
            index = options.index;
        }
        else {
            index = collection.chain().filter(this.filterView, this).indexOf(item).value();
            if (index === -1){
                index = 0;
            }
        }

        var view = new this.itemView(options);
        view.render();

        this.children[item.cid] = view;
        this.addToView(view, index);
        
    },
    removeChildView: function (item, collection, options){
        this.children[item.cid].remove();
        delete this.children[item.cid];
    },

    addToView: function (view, index){
        // append a model view to the collection view in the correct sorting order
        var $el = this.$el.find(this.contentSelector),
            $children = $el.children();
        if (index >= $children.length ){
            $el.append(view.el);
        }
        else {
            $children.eq(index).before(view.el);
        }
    },
    preRender: function (){
        // this runs before the rendering
    },
    postRender: function (){
        // this runs after the rendering
    }

});

Extending these base views I can write a very simple item view:

var ItemView = ModelView.extend({
    template: _.template(html_item),
    tagName: 'div',
    events: {
        //...
    }
});

and, of course, a very simple collection view:

var ItemsView =  CollectionView.extend({
    itemView: ItemView,
    el: $("#items"),
    events: {
        //...
    }
});

You should notice that I am using the underscore template engine (_.template).

Routing and bootstrapping

Backbone uses a router object to keep the state of your application. The state is represented by the current URL.

var Router = Backbone.Router.extend({

    routes: {
        "item/:id":        "changeitem",  // #item/id
    },
    changeitem: function(id) {
        // this is called when the URL is changed
    }
});

Like others backbone primitives you can react to an URL change handling an event (inside a view for example):

var ItemsView =  CollectionView.extend({
    itemView: ItemView,
    el: $("#items"),
    initialize: function (){
        this.listenTo(router, 'route:changeitem', this.update);
    },
    update: function (){
        // ...
    },
    events: {
        //...
    }
});

When every component is in place you can instance it and bootstrap the application.

var router = new Router(); // router instance
 
var items = new Items(); // collection instance
var itemsView = new ItemsView({collection: items}); // collection view instance
    
Backbone.history.start(); // this initialize the router

items.fetch(); // this loads initially the collection from the server

The fetch method is not your best option if you want to load models for the first time. It's better to load models inline.


I hope everything is clear. Next part: the server side!

Friday, April 26, 2013

Objects in HTML5 canvas (part 3: interacting with images)

This article is the third of a series of simple recipes that explains how to interact with objects in HTML5 canvas.
  • part 1 (Drawing shapes)
  • part 2 (Interacing with objects)
In this part we will solve the last problem: how to interact with objects with irregular shapes.

The simple answer is that you don't have to. You can wrap any image inside a rectangular box and detect where the image is transparent.

Introducing offscreen canvas

An offscreen canvas is a canvas outside the DOM. It's very useful for 2 reasons:
  • you can do complex drawing once and reuse the result with just an instruction
  • you can use it to check where an image is transparent

Let's draw

First of all I start with an images array (I used inline images, but you can use images urls):

var objs = [
    {name:'firefox',
     src:'data:image/png;base64,iVBORw0KGgoAAAA.....',
     x:30,
     y:50,
     angle:Math.PI/2,
     },
    {name:'opera',
     src:'data:image/png;base64,iVBORw0KGgoAAAA...',
     x:40,
     y:30,
     angle:Math.PI/4,
     },
    {name:'chrome',
     src:'data:image/png;base64,iVBORw0...',
     x:60,
     y:100,
     angle:-Math.PI/4,
     }
];

Then I draw each image inside an offscreen canvas and, then the offscreen canvas in the main canvas:

var i, obj;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0;i < objs.length;i++){
    obj = objs[i];
    (function (obj){
        var img = new Image();   // Creating a new img element
        img.onload = function(){
            // It's very important to wait until the image loads!!!
            // otherwise I have no clue of the real size of the image 
            ctx.save();

            ctx.translate(obj.x, obj.y);
            ctx.rotate(obj.angle);
            obj.width = img.width;
            obj.height = img.height;
            //I attach the offscreen canvas to the object
            obj.canvas = document.createElement("canvas");
            obj.canvas.width = img.width;
            obj.canvas.height = img.height;
            obj.ctx = obj.canvas.getContext('2d');
            // I draw the image on a off-screen canvas
            obj.ctx.drawImage(img, 0 , 0);
            // I draw the off-screen canvas on the main canvas
            ctx.drawImage(obj.canvas, -img.width/2 , -img.height/2);
            
            ctx.restore();
        };
        img.src = obj.src; // Set source path
    }(objs[i]));
}

Pay attention! I have applied transformations on the main canvas and not on each  off-screen canvases.

Detecting mouse clicks

Let's finish detecting on which shape a user is pointing. As usual I check each object in reverse order and transform pointer coordinates. Then I must retrieve the image from the offscreen canvas and test the color on the resulting coordinates. If the alpha value is opaque the pointer is on the image.

    // I get a single pixel
    imageData = obj.ctx.getImageData(p.x+(obj.width/2), p.y+(obj.height/2), 1, 1);
    // imageData contains r,g,b,a
    if(imageData.data[3] > 50){ // 50 is the threeshold
        log.innerHTML = 'clicked on ' + obj.name;
        return;
    }            

I have taken a pixel from the canvas using getImageData. This function returns  an array that include 4 values for each pixel (just one in my case).
The values are Red, Green, Blue and Alpha (transparency) and they have values between 0 and 255.
I set a threeshold of 50 on alpha.
This is the whole code:

canvas.addEventListener('click', function (evt){
    var rect = canvas.getBoundingClientRect(),
        posx = evt.clientX - rect.left,
        posy = evt.clientY - rect.top,
        i = objs.length,
        obj,p;
        for (; i > 0; i--){
            obj = objs[i-1];
            // translate coordinates
            p = new Point(posx, posy);
            p.translate(-obj.x, -obj.y);
            p.rotate(-obj.angle);

            imageData = obj.ctx.getImageData(p.x+(obj.width/2), p.y+(obj.height/2), 1, 1);

            if(imageData.data[3] > 50){
                log.innerHTML = 'clicked on ' + obj.name;
                return;
            }            
            
        }
        log.innerHTML = '';

}, false);


And this is the results:
  Your browser doesn't support canvas!


I hope this is helpful!

Friday, April 19, 2013

Objects in HTML5 canvas (part 2: interacting with objects)

In the previous part I have shown how to draw simple shapes to the canvas.

If you need to interact with a specific object in the canvas you have to face a problem.

Using DOM you can click on a node and the browser manages the whole interaction (triggers the event, puts the DOM node in event.target, etc.).

But, as explained before, once you have drawn an object to a canvas it become a part of the canvas. So the question is: how to detect when a user click on a specific shape?

Getting canvas related coordinates

The first obstacle to get through is getting where a user clicked on the canvas. When a user clicks you can get the mouse coordinates relative to the page and you must subtract the canvas position:

canvas.addEventListener('click', function (evt){
    var rect = canvas.getBoundingClientRect(),
        posx = evt.clientX - rect.left,
        posy = evt.clientY - rect.top;
    ...

It's not too complicate, isn't it?

Checking in reverse order

In the first part of this tutorial I put the objects to draw in an array.

var objs = [
    {name:'shape2',
     color:'green',
     x:30,
     y:50,
     angle:Math.PI/2,
     width: 40,
     height: 50
     },
    {name:'shape1',
     color:'red',
     x:40,
     y:30,
     angle:Math.PI/4,
     width: 30,
     height: 40
     }
];

Then each shape is drawn in order over the previous.
For this reason I have to check shapes in reverse order, from the object in foreground to the one in background.

        for (i = objs.length - 1; i >= 0; i--){
            obj = objs[i];
            ...

Pointer transformations

Now I have pointer coordinates and shape transformations:

    {name:'shape1',
     color:'red',
     x:40, // translation x
     y:30, // translation y
     angle:Math.PI/4, // rotation
     width: 30,
     height: 40
     }

How to detect if pointer coordinates are inside this shape?

My solution is a bit imaginative but it seems to work well.
I apply transformations to pointer coordinates. These are the opposite that I have applied to the object before drawing it to the canvas. Then I check if the new pointer coordinates are inside the object shape pretending that the shape has drawn around 0, 0.

// pointer transformation
p = new Point(posx, posy);
p.translate(-obj.x, -obj.y);
p.rotate(-obj.angle);

if (p.x > -(obj.width / 2) && p.x < obj.width / 2 && p.y > - (obj.height / 2) && p.y < obj.height / 2){
    log.innerHTML = 'clicked on ' + obj.name;
    return;
}            


I wrote this simple object to help with transformations (see part 1 for an explanation on transformations):

var Point = function (x, y){
    this.x = x;
    this.y = y;
};

Point.prototype.rotate = function (angle){
    var x, y;
    x = this.x*Math.cos(angle) - this.y * Math.sin(angle);
    y = this.x*Math.sin(angle) + this.y * Math.cos(angle);
    this.x = x;
    this.y = y;
    return this;
};

Point.prototype.translate = function (x, y){
    this.x = this.x + x;
    this.y = this.y + y;
    return this;
};

This is the whole code:

canvas.addEventListener('click', function (evt){
    var rect = canvas.getBoundingClientRect(),
        posx = evt.clientX - rect.left,
        posy = evt.clientY - rect.top,
        i, obj,p;
        // I get the position of the pointer
        // relative to the canvas
        for (i = objs.length - 1; i >= 0; i--){ // cycling in inverse order
            obj = objs[i];
            // pointer transformation
            p = new Point(posx, posy);
            p.translate(-obj.x, -obj.y);
            p.rotate(-obj.angle);

            if (p.x > -(obj.width / 2) && p.x < obj.width / 2 && p.y > - (obj.height / 2) && p.y < obj.height / 2){
                log.innerHTML = 'clicked on ' + obj.name;
                return;
            }            
            
        }
        log.innerHTML = '';

}, false);

This is the result (try to click on a shape):
Your browser doesn't support canvas!
In the next part I'll add a more fine control on images using off-screen canvases. Stay tuned!!!