Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, February 25, 2015

High performance animations (a few tricks)

The web browser is capable of very smooth animations, but there are a few gotchas. Here is what you should know.

jQuery

With jQuery animations went mainstream. But jQuery.animate is possibly the less efficient way for animating elements nowadays:
It can be still useful on old browsers or in specific cases. Better not using it on mobile browsers.

CSS transitions and animations

Native animations runs usually faster than JS ones. So it is quite obvious to use them when possible. There are plenty of tutorial on how to use them so google for it!

Composite layer css properties

When you change a CSS property you trigger some operations in the browser. These are:

  • recalculating sizes and positions (layout)
  • redrawing elements on the screen (paint)
  • composite all elements together (composite)

The topmost operations triggers the ones below. Furthermore the more elements are involved the worst the animation is , performance wise.
You can visualize and debug this process in the useful timeline panel (inside Chrome developer tools).
The trick here is to use css properties that triggers only the composite step. These are opacity
and transform. This is article contains what you need to know.
Sadly it is not enough to use these for getting the performance jump, you should also trigger the creation of a new composite layer using these CSS rules:

.will-change{
    transform: translate3d(0, 0, 0); 
    perspective: 1000;
    backface-visibility: hidden;
}

For a better support you can add these browser prefixes:

.will-change{
    -webkit-transform: translate3d(0, 0, 0); /*old chrome and safari*/
    -o-transform: translate3d(0, 0, 0); /*old opera*/
    -moz-transform: translate3d(0, 0, 0); /*old FF*/
    -ms-transform: translate3d(0, 0, 0); /*IE9*/
    transform: translate3d(0, 0, 0);
    -webkit-perspective: 1000;
    -o-perspective: 1000; /*old opera*/
    perspective: 1000;
    -webkit-backface-visibility: hidden;
    -o-backface-visibility: hidden; /*old opera*/
    backface-visibility: hidden;
}

Doing this opacity and transform are managed by the GPU if possible.
This can be a bit awkward and for this reason browser vendors have created a new css rules: will-change.
This will make the browser know that an element is going to change and to put it inside a compositing layer (this is not yet widely available so sadly, for now, it is better to stick with the hack).

Request Animation Frame


The way js animations work is changing a numeric CSS property over time. The only way to schedule an event in js was setTimeout (and its brother setInterval). As I mentioned they are still used by jQuery.
A while ago browser vendors introduced "requestAnimationFrame". It is a much better way to do it as it execute a piece of code right before the page refresh (approximately 60 times a second).
This is a polyfill for any browser (in the worst case it uses setTimeout).

If your animation depends on user interactions it can be a good idea to throttle the changes to the CSS using requestAnimationFrame. In this example I am using a queue with a simple policy that returns only the last function discarding the others.

function lastOne(q){
    return q.length ? [q.pop()] : [];
}

function getRenderingQueue(policy){
    var queue = [];
    var isRunning = false;
    policy = policy || function (q){return q;};

    var render = function (){
        var f;
        queue = policy(queue);
        isRunning = false;
        while (f = queue.shift()){
            f();
        }
    };
    return {
        empty: function (){
            queue = [];
        },
        push: function (func){
            queue.push(func);
            if (!isRunning){
                isRunning = true;
                window.requestAnimationFrame(render);
            }
        }
    }
}


var renderingQueue = getRenderingQueue(lastOne);

renderingQueue.push(function (){
    //changing a piece of CSS
});


Depending on your application you can decide using a different policy.

This is it, I'll soon put this in context.

Thursday, January 15, 2015

Why I have stopped using requirejs (and you should too)

I have used requirejs extensively and I have written many posts about it. I think it is very ingenious and well designed.
It tries to solve more than one problem at the same time (in a very elegant way) but nowadays these problems are not so important and they have better solutions.

Loading scripts asynchronously

This was one of the main selling point of requirejs in the past. Now it is not necessary anymore. It is much better moving (back) the script tags on the top and use the async attribute as described by this great article. The async attribute now is very well supported !

Loading dependencies

Requirejs can dinamically load dependencies when they are required. But often you want to have the control. Sometime is better to include a library when you load the page (bundling more than a library together, for having them saved in the cache) and sometime you want to load it on demand. In case it is very easy do something like:

var script = document.createElement('script');
script.src = "http://www.example.com/script.js";
document.head.appendChild(script);

Isolate dependencies

Requirejs is even able to run 2 different versions of the same library. But is a feature rarely used and to be honest in 99.9 % of the cases using the module pattern is more than enough.

The only issue

The only issue of having all these asynchronous bundles (using the async attribute) is managing the execution order. You can use a tiny library like this one:

(function (w){

var go = {}, wait = {};
w.later = function (dep, func){
    if (go[dep]) func();
    else {
        wait[dep] = wait[dep] || [];
        wait[dep].push(func);
    }
}

w.later.go = function (dep){
    var funcs =  wait[dep] || [], l = funcs.length;
    delete wait[dep];
    go[dep] = true;
    for (var i = 0; i < l; i++){
        try{
            funcs[i]();
        }
        catch (e){
            console && console.error(e);
        }
    }
}
}(window));

This could be the only JS to be loaded synchronously. For maximum performances you can also minify it and inline in the HTML.
Then you can manage the dependencies at execution time:

later('foo', function (){
   // waiting for the bundle named foo (it is an arbitrary string)
});

You only need to put this instruction at the end of the bundle "foo":

later.go("foo");

There are still valid use cases for requirejs but I suggest to keep your build process lean, tweak performances by hand, use the async attribute and the module pattern.
Simpler and more performant !

Edited: and what about "defer"?

This article suggests to use async and defer together for improving performances on older browsers. I suggest to not do that, unless you know what your script is doing. This is because of this bug. The bug is even worst of what it seems, if you inject a script tag inside a DEFERred script the execution will stop waiting for the injected script to be downloaded and executed. So be careful!


Thursday, April 17, 2014

A trip into Clojure, lesson learned

In my current job I had the chance to learn and use Clojure (this is the experience reported by a former collegue). Having worked with Python and Javascript I had consided myself well skilled in functional programming. But working with a more opinionated functional programming language was an eye opener. The benefits? robustness, better code reuse, a more organic workflow.

My main takeaway is that I can apply the lesson learned to Python and Javascript (and many others) as well. Let's see how.

Languages

Many languages enforce a specific point of view. Java for example with its pervasive object orientation enforce to model problems in objects. Python tries to please everyone with a solid OO implementation and a good deal of functional constructs. Javascript is similar (but with a different OO implementation).
Clojure, from this point of view, is more like Java: it enforces a specific way to model problems: a functional model.

Functions

Of course functions are first class citizen in a functional language so they can be stored in variables, passed as argument etc.
This allows a lot of useful programming patterns. These are just few examples:

  • Passing a callback: in event oriented programming (like events in browser or node.js) it's useful to pass a specific callback to run after an event
  • Decorator: you wrap a function in another function (useful for access control, memoization etc.). In Python there is a programming feature called "decorator" that makes easier to use this pattern.
  • Lazyness and partials: a function retuning not the actual result but another function that return the result. Useful to defer the actual task and if you need only a part of the result.

A brilliant example of what functional programming allows are wsgi middlewares (in the Python world) and Connect middlewares (in the node.js/Javascript world). As a matter of fact you can find a similar pattern in Clojure ring.

No objects - nothing enforce a local state

While the classic OO tries to encapsulate logic and state in the same entity (objects) a functional language keeps the two things well separated. This seems to be weird if you are used to OO but it has a lot of sense.
It is easy and more predictable to test the code because you are sure there is no mutation of the local state during the method calls. Any function has arguments and output: there is no side effect based on value of "this". Actually in Clojure you can have side effects (mutating atoms for example) but this is an exception, not the rule. And this is clearly explicit.

Types and common interface

Standard maps/lists offer a common and simple interface to a lot of generic functions. In the classic OO every object has a different interface requiring specific code to interact with.

In Javascript there are fantastic libraries like underscore, lodash to interact with standard arrays, objects (intended as maps in this case). You can also use hash maps and sets (Ecmascript 6). If you use  field descriptor you can access getters and setters using the usual semantic.

If you use Python, you should use more list an dict and less custom objects. Python can help you to keep the interface simpler using field descriptors and operators overloading. There are a lot of functional built in (like zip, map, filter, list comprehensions ...) and the fantastic itertools library.

(Im)Mutability

An immutable object cannot be changed. Any change creates a new object.
Mutable objects are a dangerous source of bugs. It's very easy to change an object passed as argument or by another function call without realizing that you are changing permanently the original object. This is a classic python gotcha.
It's not only a newbie's mistake: I have spotted the same nasty bug in Backbone.js.

In this case Clojure shines because everything is immutable by default.
If you use Python, you should never mutate an object/dictionary/list passed as argument. If you really need to do that, clone it before. Remember that list comprehensions, slice operator, and many built-ins return a brand new object and are safe. But it is better to check the doc because for example the "sort" method mutate the original list and the "sorted" built-in no.

The same advice is valid for Javascript too. Check the usual underscore and lodash for  clone and deepClone method. Remember that some array method returns a brand new array. This is a shallow clone but sometimes is good enough. A fantastic option is to use mori a library to use Clojure(script) data type and sequences in Javascript.

Lazyness

Working with sequences in Clojure is amazing because any operation is deferred. This is memory and computational efficient. This is not a new thing if you use Python generators, itertools or the new Javascript iterators and the for-of statement (ES 6). You can also use the Clojure sequence library with the aforementioned Mori library.

Development process

The functional approach (in my personal opinion) allows to develop in a more gradual way. While in the OO you have better results deciding the object model upfront, this is a bit complex in the long run. Some changes will require to move methods around the class hierarchy, create common base classes. And this kind of refactoring often invalidates a lot of unit tests too. So you often ends with small patches and code duplication.
The evolution of a functional program can be a bit chaotic but changes are more granular and it's easier to reuse code without doing a lot of impact.


This is the lesson learned: be more functional!

P.S. This is a nice book if you want to improve your Functional Javascript skills

Sunday, March 23, 2014

When scripts should run?

A quick walkthrough on when executing a script in the browser.

A lot of examples on the internet show to wrap the code inside the jQuery "ready" event handler. It is not always the case. As a matter of fact you can execute a script in three different fashions:
  • immediately
  • in the ready event handler
  • in the load event handler
  • under another event handler (but this is a different story though)

Immediately

You can execute a script immediately if your script doesn't rely on the DOM, or rely on a fragment of DOM that is already been loaded (because is placed before your script).
I think this is often the preferred case.

JQuery ready

The jQuery ready event handler uses the  domcontentloaded event but is guaranteed to be executed right away if this event is already been fired.
"The handler passed to .ready() is guaranteed to be executed after the DOM is ready"
You should execute your script here if it runs before the fragment of DOM targeted by the script. Given this, if you are loading synchronously you should definitely put the script at the bottom of the HTML and just execute it immediately.

On load

There are rare cases when you need the CSS and images loaded before executing the script. A suggestion: avoid it if you can! For example you could (and definitely should) add the width and height attribute on any img and you can use a bit of inline css styling (in some edge case).
In the few cases you really need this you can use the load event handler.

Asynchronous loading

If you use requirejs you really don't have a clue on when your script is executed. Luckily enough executing it immediately or inside a jQuery ready event is always safe. It's not so using the load event.
Your script could be loaded after the load event is already been fired. For this reason is a good idea to check it and, in case, executing the script immediately.

function mycode(){
   ...
}

if (document.readyState == "complete"){
    mycode();
}
else {
    $(document).load(mycode);
}

Ajax fragments

When you load or create a new fragment of html sometimes you need to run the some code against the new fragment. This can be avoided the vast majority of time using event delegation adding your event handlers to a wrapper node (or to the document itself). If you really need to manage this I suggest to generate a custom event to manage these cases. For example:

// loading a fragment
var $result = $("#result")
$result.load("ajax/test.html", function (){
    ...
    $result.trigger('nodeloaded');
    ...
});

...
// trigger on the document ready 
// for the whole document
$(document).ready(function (evt){
    $(document).trigger('nodeloaded');    
});

...

// manage the event
$(document).on("nodeloaded", function (evt){
    $('.your-class', evt.target).yourplugin();
});

You can find something similar used in jquery mobile.


Sunday, January 26, 2014

Requirejs: edge cases


I have already written about requirejs in this post.
In this new post I'm going to explain something you should know using require in complex environments.

You definitely should use the optimizer

Not using the optimizer in a production environment is highly discouraged.

To explain why, it can be useful thinking about how requirejs works:
All the modules together form a dependency tree. The process of loading this tree is not completely parallel because requirejs is aware of specific dependencies only after loading a module.
Requirejs optimizes this process executing a module only once and caching its result.
The optimizer simply merges a group of modules in a single file and this makes the process much faster.

Inline scripts

Sometimes you'll need to add online scripts to the HTML. Doing this you should consider that your module could be not loaded yet. To fix this problem you can "require" your bundle as a dependency before running the code:

require(["app"], function (){ // app is the name of the bundle
    require(["yourdependency"], function (){
        //inline script
    });
});

But there is another problem!
Many examples shows to put your requirejs configuration inside the first module.
Sometimes you'll need a specific configuration to load your module (for example the baseUrl). But the configuration could not be available in your inline scripts (it's async!).

There is a trick for this: requirejs allows to load the configuration in a synchronous way. You just need to define a global object "require" with the configuration right before loading requirejs script.

<script>
var require = {
    "baseUrl": "http://example.com/js/lib",
    "paths": {
      "app": "main/app"
    },
    "shim": {
        ...
    }
};
</script>
<script data-main="scripts/main.js" src="scripts/require.js"></script>

Mixing synchronous and asynchronous scripts

Performance wise all the scripts should be loaded asynchronously but real world applications need some compromise.
A typical case is using the infamous document.write that wipes out the page when executed asynchronously.

In this slideshow @slicknet explains why loading scripts in different positions.

But mixing synchronous and asynchronous script can be tricky. How can do it safely?

First of all be careful where you load the requirejs script in the page. Many libraries check for the presence of the "define" global variable to be loaded asynchronously (using the UMD pattern):

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['b'], factory);
    } else {
        // Browser globals
        root.amdWeb = factory(root.b);
    }
}(this, function (b) {
    //use b in some fashion.

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};
}));


Jquery for example is AMD compatible so, if you load requirejs before jquery, this will behave in a different way.
My suggestion is to concatenate all the synchronous files of your application in a single script, putting requirejs in the last position.

Second problem: what happen if you are requiring a module and, in this particular page, this module is already loaded synchronously ?
Requirejs will download the module again, this time as a module. This is not ideal so you need to trick requirejs prepending to our main module something like this:

define('jquery', [], function() { // jquery is loaded synchronously before this code
    return jQuery;
});

With the previous code requirejs will use the global jquery instead of requiring a new jquery module to the server.
I am not advocating to load jQuery syncronously. This is just an example!
Another issue: the optimizer will include all the scripts that in your particular case are synchronous.
You need to exclude these files from the optimization (this is an example using the grunt-contrib-requirejs task):

    requirejs: {
      dev: {
        options: {
        "appDir": "www",
        "baseUrl": "js/lib",
        ... other options ...
        "modules": [
            {
                "name": "app",
                "exclude": [
                    "jquery",
                    ... other exclusions ...
                ]
            },
            ... other bundles ...
          ]      
        }
      },

Loading dynamically

In some case you'll want to download a different group of modules in a more dynamic way. Based on a certain configurations or user event (like in this example)
For doing this you can create one or more different bundles (with the optimizer).
You need to remember to exclude from the bundles the resource that should be already loaded in the page (use the previous option).

Scripts not bundled

In some case you don't want to include your file in a bundle because is served by a CDN or directly from your application (for example socket.io). The requirejs optimizator uses the "empty:" option to manage this:

    requirejs: {
      compile: {
        options: {
          mainConfigFile: "static/js/main.js",
          baseUrl: "static/js",
          name: "main",
          paths: {
            'socketio': 'empty:',
            'backboneio': 'empty:'
          },
          out: "static/js/main-built.js"
        }
      }
    }

Requirejs is a very good choice to manage scripts loading and dependencies. I hope to have brought light in some of the dark spots of using this in a complex environment.

Friday, October 18, 2013

Reusable javascript modules with Bower

In a previous post I have used require.js to download javascript files and optimize them.
Here I'll introduce a useful tool to manage your javascript and css assets. But first of all let's talk about modules definition in Javascript.

Universal module definition

At the moment there is no standard way to define a module (we are waiting for EcmaScript6) but you can easily define your module in a way compatible with AMD, UMD and regular script import. Just pick one of these snippets. I recommend to use one of those because declaring object in the global namespace is not a good practice and libraries like requirejs can help to load and optimize your scripts.

Bower

Bower is a package manager designed for the web. You can install it using:

npm install -g bower

And then start downloading your first package (jquery for example):

bower install jquery

You'll find jquery in the jquery folder inside the "bower_components" folder. Bower packages are versioned so you could (and should) specify what version install.
bower install jquery#1.10.2
If this package has some dependencies (other bower packages of course) those will be installed in the same "bower_components" folder. For those who are using node.js: be aware that it is quite different from how npm works! In this case all the dependencies are resolved and flatten in the same folder.

Bower package

A bower package, in fact, is a simple folder with a bower.json file:
{
  "name": "mypackage",
  "version": "0.0.1",
  "main": [
     "script.js",
     "style.css"
  ],
  "homepage": "https://github.com/User/myproject",
  "authors": [
    "Donald Duck "<donald.duck@gmail.com>";
  ],
  "description": "an example package",
  "keywords": [
    "js",
    "css",
  ],
  "license": "private",
  "private": true,
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "lodash": "~1.3.1",
  }
}
Let's see the most important fields:

name: the name of the package

version: the version of the package. It should be the same of the tag on git.

main: these are the main files of your project. For example a jquery repository has a lot of stuff (unbuilded file, test, fixtures etc.) but the main file is just jquery.js.

dependencies: an array of bower packages needed to run this one. You should always specific the version using this syntax.

Bower repository

The published packages are just git tags with a bower.json. The bower command  anyway uses a central repository to store the metadata (name, url of repository, keywords etc.). This repository is on https://bower.herokuapp.com/. If you have a public project you can publish on the central repository using:
bower register mypackage https://github.com/user/mypackage.git
The versions available will be taken from the available tags on you repo.

Running your own repository

Let's say you are working on a project and you don't want to share every package you are working on.
You can easily set up your own bower registry and configure bower to use it. You can do this putting a ".bowerrc" in your working directory (or in your home):
{
    "registry": {
        "search": ["http://bower.myserver.com", "https://bower.herokuapp.com/"],
        "register": "http://bower.myserver.com"
    }
}

This instructs bower to download packages from your server or the official one (the first has the priority), and to register the packages on your server only.

Automate everything !

Using grunt-bower-task you can create a build step that install all the dependencies required by your bower.json and copy all the files defined in "main" in a folder. If you use require.js you can also use grunt-bower-requirejs to build  the require.js configuration automatically.

I think this is enough to start working with bower. Enjoy!




Thursday, July 25, 2013

Server side modules with Architect

After my last notes on a client side modular architecture using require.js I'll talk about server side modules using Architect.

Modules

In my opinion every application (not only the bigger ones) needs to be divided into interdependent modules. This helps a lot when you deal with testing and enhancing your application.
In node.js applications, you will see and use this pattern very often:

//import a module
var Database = require('./db');

// initialize a module using some options 
var db = new Database('http://my.db.connection');

// initializing a module injecting a dependency 
var usermanager = require('./usermanager')(db);

But what if you want to use this module in other applications ? In this case you should make an npm independent package for each module, of course. And, in the main application you would initialize each package in the proper order. This is repeatitive and tedious furthermore, when the number of the packages starts to get bigger, initializing each module in the proper order can be an issue.

From modules to plugins

Architect uses a simple declarative syntax to explain the interconnections between packages. It also starts the system in the correct order initializing each package just once.
I recommend to read the documentation on github. It's very clear and detailed.

Express.js and Architect

I have set up a simple express.js/architect boilerplate to show how to use Architect to make an extensible express.js application.


I hope this will be useful ...

P.S.
A friend of mine suggest me to use a git subtree for each package. Nice idea!


Thursday, July 18, 2013

Client side modules with require.js


In this post I will show you how to use Require.js to split a project into simple and manageable modules.

UMD and AMD

I really didn't want to dive into differences of these 2 module systems but I think it's very important to realize of what module system we are talking about.

UMD is the module system used by node.js. You define modules doing this (foobar.js):

module.exports = {
    foo: 'bar'
};

And load a module doing this:

var foobar = require('./foobar');
console.log(foobar.foo); // prints bar

You can use UMD in the browser using browserify.
If you usually work with Javascript in the browser you will notice two issues:
  • the exports object would be overwritten every time by differents modules
  • it uses a synchronous approach
As a matter of fact it cannot work in the browser without a build step (and this is the browserify's task).

AMD instead is designed from the ground up to work in the browser.

Saying this I am not advocating one of these systems. They are both very useful even though they use different approaches.

I started by explaining UMD because, unfortunately, both systems use a function called "require".
Now that you can't be fooled anymore by this let's go on.

What is an AMD module

An AMD module must be contained in a single file and is encapsulated by the global function define.
"define" takes two parameters: an array of dependencies and the actual module code.

//module3.js
define(['module1', 'module2'], function(module1, module2) {
    'use strict';

    var namespace = {};
    
    return namespace;
});

In this example I have defined a module called "module3". This module needs module1 and module2 to run.
The return value of define will be returned if another module requires module3.
module1 and module2 are resolved loading with AJAX module1.js and module2.js (both AMD modules).
The job of require.js is basically to resolve the dependency tree and to make sure that every module would be run just once.

A module has a pair of interesting properties:

  • It is loaded the first time is required by another module.
  • not a single variable is added to the global namespace. For this reason you can even use different versions of the same library if you need to

Bootstrap and configuration

After defining modules you will need to bootstrap your application (configure and load the first module). For doing this you will define in your page a script tag with require.js and the url of the bootstrap script (main.js).

<script data-main="/js/main" src="js/vendor/require.js"></script>

After loading require.js it will load the "main.js" bootstrap using ajax. From this point every script will be loaded asynchronously and the DOMContentLoaded event (the jquery ready event) will be fired independently from the script loading.

Main.js is made of 2 part. The first one is require.js configuration:

require.config({
  baseUrl: "js/",
  paths: {
    jquery: 'vendor/jquery-1.9.1',
    underscore: 'vendor/underscore',
    backbone: 'vendor/backbone',
  },
  shim: {
      underscore: {
          exports: "_"
      },
      backbone: {
          deps: ['underscore', 'jquery'],
          exports: 'Backbone'
      },
      'jquery.bootstrap': {
          deps: ['jquery'],
          exports: '$'
      }
    }
});

Here are the most important parameters:
baseUrl: this is the path used to resolve modules.. So if you require "module1" this will be loaded from "js/module1.js".

paths is very useful to define script that are in some other paths. When you require "jquery" will be loaded the script "js/vendor/jquery-1.9.1.js".

Shims

Until now I assumed that every script is an AMD module but this is not always true.
require.js shim option allows to wrap automatically a non AMD script into an AMD define.

"deps" are dependencies to be injected and "exports" is the value to be returned:

For example your backbone.js will become:

define(['underscore', 'jquery'], function (_, $){

..actual backbone.js source ...

return Backbone;

});

The trick works even when you have to add attributes to an existing object (like defining a jquery plugin):

define(['jquery'], function ($){

$.fn.myJqueryPlugin = function (){
};

return $;

});

This is the case of Twitter bootstrap.

require

The second part of main.js is the actual bootstrap. It loads and execute the first module.

require([
  // Load our app module and pass it to our definition function
  'app',
], function(App){
  // The "app" dependency is passed in as "App"
  App.start();
});
The app module will start a chain of loading that will load the entire application's scripts.

The useful text plugin

The text plugin allows you to add text files as dependencies and this is very useful for client side templating.
Just add "text" in the path config:

require.config({
  ...
  paths: {
     ...
    text: 'vendor/text'

and you can load your templates:

define(['underscore', "text!templates/template.html"], function (_, template_html){
    var template = _.template(template_html);
    ...
});

You can also write your own plugin as described here.

Script optimization

Using a lot of modules have an obvious drawback: the time spent to load these modules in the browser.
Require.js comes with a useful tool for optimizing scripts: r.js. It analizes, concatenates and minifies all the dependencies in one single script.

I warmly recommend to use a build step to make this operation automatically.

I use grunt and a grunt plugin to automate everything.

Installing grunt and the require.js optimizer plugin

Grunt is structured in 2 different modules: "grunt-cli" and "grunt" and a series of plugins. "grunt-cli" can be installed globally:

npm install -g grunt-cli
grunt and the plugins should be installed locally pinning a release version. This system allows to use different versions and plugins for each project.
npm install grunt --save-dev

npm install grunt-contrib-requirejs --save-dev

The save-dev option adds the modules in the package.json under the "devDependencies" key and using the latest release.
...
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-requirejs": "~0.4.1"
  },
...

You can also do this manually and launch "npm install".

Grunt configuration

Grunt needs a configuration file called Gruntfile.js this is an example from a past project of mine:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    requirejs: {
      compile: {
        options: {
          mainConfigFile: "static/js/main.js",
          baseUrl: "static/js",
          name: "main",
          paths: {
            'socketio': 'empty:',
            'backboneio': 'empty:'
          },
          out: "static/js/main-built.js"
        }
      }
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  // Default task(s).
  grunt.registerTask('default', ['requirejs']);

};

In the "requirejs" configuration I have:
mainConfigFile: the path of the bootstrap script
baseUrl: the same as configured in the main.js configuration
name: the name of the main script
paths: in this section I added a pair of script to not be included in the optimized script. These 2 files are served directly by my node module. You can also do the same for script served through a CDN or an external service.
out: the output file

"registerTask" allows me to launch the whole optimization step with the "grunt" command (using no options).

At the end of the task I can load my new optimized script using:

<script data-main="/js/main-built" src="js/vendor/require.js"></script>
I think this is all. Stay tuned for the next!

Edit: If you liked this you'll probably be interested in this other blog post on require.js edge cases.

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!!!

Friday, January 11, 2013

Backbone.occamsrazor.js

Despite of the awful name this is one of the nicest experiments I ever done (at least in Javascript :-) ).
I used occamsrazor.js to enable heterogeneous collections in backbone.js.

What ?

Backbone.js api is based on a RESTful architecture. This architecture is based on "resources" and "verbs". Resources are atomic unit of information identified by URLS. Verbs are an unified interface to make basic operations on resources (GET, PUT, POST, DELETE). 
3 of these VERBS operates on a single resource (GET, PUT and DELETE). POST operate on a special resource called "collection". A POST request on a collection causes the creation of a new resource. Backbone.js simplify the work allowing to issue a GET request to a collection. It is very useful to fetch all the models contained in a collection.
All of these client/server exchanges use basic JSON objects. These objects are just a bunch of attributes put together without a notions of the original model.
In order to transform this bunch of attributes in a full fledged object (with methods, prototype etc.) the backbone collection makes a simple assumption: all the object contained in a collection must be of the same type (model).

A positive side effect: models and views are now plugins!

occamsrazor.js enable collections formed by different models. As a (positive) side effect the models and model views are now plugins. I wrap the results in a simple backbone ehnancement.

Models and collections

Let's start with a simple empty collection:
    var shapesCollection = new Backbone.Occamsrazor.Collection;
With classic backbone collection you should define the model of the objects contained.
With Backbone.Occamsrazor.Collection instead you set what kinds of models it could contain. But first of all define some validator:
    var hasWidth = function (obj){
            if (obj instanceof Backbone.Model){
                return obj.has('width');
            }
            return 'width' in obj;
        },
        hasHeight = function (obj){
            if (obj instanceof Backbone.Model){
                return obj.has('height');
            }
            return 'height' in obj;
        },
        hasRadius = function (obj){
            if (obj instanceof Backbone.Model){
                return obj.has('radius');
            }
            return 'radius' in obj;
        },
        hasWidthHeight = occamsrazor.chain(hasWidth, hasHeight);
These validators take an object and returns a positive number if the object has a feature.
In this case is convenient validate both a simple object and a Backbone model.
You can find further explanations about validators in the occamsrazor.js documentation.
    shapesCollection.model.addConstructor(hasWidth, Backbone.Model.extend({
        getArea: function (){
            var w = this.get('width');
            return w*w;
        }
    }));

    shapesCollection.model.addConstructor(hasWidthHeight, Backbone.Model.extend({
        getArea: function (){
            var w = this.get('width'),
                h = this.get('height');
            return w*h;
        }
    }));

    shapesCollection.model.addConstructor(hasRadius, Backbone.Model.extend({
        getArea: function (){
            var r = this.get('radius');
            return Math.round(Math.PI * r * r);
        }
    }));
From now the collection can work with three kind of models transparently:
    shapesCollection.add([{width: 10, height: 5}, {width: 10}, {radius: 3}]);
    
    console.log(shapesCollection.at(0).getArea()); // 50
    console.log(shapesCollection.at(1).getArea()); // 100
    console.log(shapesCollection.at(2).getArea()); // 28

Views

If you use an heterogeneus collection you will surely need something analogous for the views.
You will probably need a different view for each model. This works almost the same as models. First create a collection view::
    var shapesView = new Backbone.Occamsrazor.CollectionView({collection: shapesCollection, el: $('#myid')});
And then add the views:
    shapesView.itemView.addConstructor([null, hasRadius], Backbone.Occamsrazor.ItemView.extend({
        tagName:  'div',
        render: function (){
            this.$el.html('The area of the circle is ' + this.model.getArea());
            return this;
            
        }
    }));

    shapesView.itemView.addConstructor([null, hasWidth], Backbone.Occamsrazor.ItemView.extend({
        tagName:  'div',
        render: function (){
            this.$el.html('The area of the square is ' + this.model.getArea());
            return this;
        }
    }));

    shapesView.itemView.addConstructor([null, hasWidthHeight], Backbone.Occamsrazor.ItemView.extend({
        tagName:  'div',
        render: function (){
            this.$el.html('The area of the rectangle is ' + this.model.getArea());
            return this;
        }
    }));
You should notice that I used Backbone.Occamsrazor.ItemView as view constructor function. This is nearly identical to Backbone.View: the only difference is in the way the model is passed to the costructor.
This emphasizes the fact that you must pass the model as argument and allows occamsrazor to pick the right view for a that model.

I have prepared a simple demostration of the potential of this library here. This is the classic todomvc application by Addy Osmani. The interesting part is in how it is simple adding plugins to enhance the application without touching the original code.

I hope this makes clear how occamsrazor.js can be helpful !


Thursday, December 20, 2012

Occamsrazor.js 2.0 API ehnancement

I released version 2.0 of occamsrazor.js. My goal is to further simplify the API. This example is taken from my last post:

//mediator

var pubsub = occamsrazor();

// from now a validator is a simple function
var is_archive = function (obj){
    return 'getNumbers' in obj;
};

// the archive object

var archive = (function (){
    var numbers = [];
    return {
        getNumbers: function (){
            return numbers;
        },
        addItem: function (number){
            numbers.push(number);
            // this notify the event to the mediator
            pubsub.publish('changed', this);
        }
    };
}());

// the printsum isn't changed

var printsum = (function (){
    return {
        print: function (n){
            console.log(n);
        },
        sum_and_print: function (archive){
            var i,sum = 0;
            for(i = 0;i < archive.length; i++){
                sum += archive[i];
            }
            this.print(sum);
        }
    };
}());

// subscribe the event
// subscribe is an alias of "add" and "on"

// the list of validators now is before the function
pubsub.subscribe(["changed",is_archive], function (evt, archive){
    printsum.sum_and_print(archive.getNumbers());
});

//you can use a single string instead of a function as a validator

Thursday, December 6, 2012

Mediator pattern with occamsrazor.js

The mediator design pattern can be very useful to decouple a group of objects. Let's see how.

Let's say we have two very simple objects. The first is an archive of numbers:

var archive = (function (){
    var numbers = [];
    return {
        getNumbers: function (){
            return archive;
        },
        addItem: function (number){
            archive.push(number);
        }
    };
}());

The second object prints the sum of the numbers of the previous object:

var printsum = (function (){
    return {
        print: function (n){
            console.log(n);
        },
        sum_and_print: function (archive){
            var i,sum = 0;
            for(i = 0;i < archive.length; i++){
                sum += archive[i];
            }
            this.print(n)
        }
    };
}());

Ok. Now we need to recalculate and print the sum each time a new item is added to the archive. The first solution is straightforward:

...

        addItem: function (number){
            archive.push(number);
            // we call directly the function
            printsum.sum_and_print(archive);
        }
...

This could be a solution but It has a drawback: we bind explicity the two objects together. With many objects and direct dependencies this could be very difficult to manage. Moreover, chaging or adding other dependencies could translate in changing extensively the (already tested) code.

The mediator

The mediator is an object that mediates between other objects. Instead of calling functions directly we notify events to the mediator. The mediator calls every function that is subscribed to a certain event.
Let's rewrite the example using occamsrazor.js to build a mediator:

//mediator

var pubsub = occamsrazor();

// we need 2 validators, one for the event and the second for the object

// this validate the type of the event

var is_changed_event = occamsrazor.validator(function (evt){
    return evt === 'changed';
});


// this validate the type of the object

var is_archive = occamsrazor.validator(function (obj){
    return 'getNumbers' in obj;
});


// the archive object

var archive = (function (){
    var numbers = [];
    return {
        getNumbers: function (){
            return numbers;
        },
        addItem: function (number){
            numbers.push(number);
            // this notify the event to the mediator
            pubsub.publish('changed', this);
        }
    };
}());

// the printsum isn't changed

var printsum = (function (){
    return {
        print: function (n){
            console.log(n);
        },
        sum_and_print: function (archive){
            var i,sum = 0;
            for(i = 0;i < archive.length; i++){
                sum += archive[i];
            }
            this.print(sum);
        }
    };
}());

// subscribe the event

pubsub.subscribe(function (evt, archive){
    printsum.sum_and_print(archive.getNumbers());
}, [is_changed_event,is_archive])

Build a mediator with occamsrazor.js has another advantage: events are notified only for the objects that pass every validator.

Next challenge: try to integrate occamsrazor.js with backbone.js 
Stay tuned !

Tuesday, October 30, 2012

Enhancing Backbone.js with Occamsrazor.js

WARNING. This article is an early experiment ! This way to enhance backbone.js is much better!

In this post I want to share a little experiment I made with Backbone.js and Occamsrazor.js. But before that I want to explain briefly what Backbone.js and Occamsrazor.js are.

Backbone.js

Backbone.js is a Javascript library useful to build structured UI. It's main role is to coordinate one or more models with their visual representations (views). It also manage the data exchange with the backend. (It is designed to be used in the frontend).
The core of Backbone.js is made of three powerful types of object:
  • models
  • collections
  • views
The model is an atomic unit of data. The collection is a group of objects that share the same model. The view keeps updated the visual representation of a model or a collection. The coordination between each these object is decoupled using events (observer pattern).

The web is plenty of Backbone.js documentation. For example:

Occamsrazor.js

Occamsrazor.js is a plugin system I wrote some time ago. I wrote about that here and here.

Why use these libraries together ?

With Occamsrazor.js a collection can contain objects of different types. To say the truth, in my experiment there is only one type of model but it can behave differently based on its fields.
For example we can decide which view is more appropriate.

The results

The demo is here (it is quite funny, I put in box2d and other libraries).
The "CanvasPlayView" view is responsible to draw all of the bodies on a canvas. In the render method we found this:

        models.bodies.each(function (element, index){
            var pos, x, y, angle;
            pos = positions[element.id];
            if (! pos){
                return;
            }
            x = pos.x;
            y = pos.y;
            angle = pos.angle;

            canvasLayer.ctx.save();
            canvasLayer.ctx.translate(x * canvasLayer.scale, y * canvasLayer.scale);
            canvasLayer.ctx.rotate(angle);

            plugins.drawer(element).render(canvasLayer);

            canvasLayer.ctx.restore();

        });

"Plugin.drawer" is not a regular function. It's a plugin!
This plugin is added in the rect module (the module containing all the plugins for the rectangular bodies) :

plugins.drawer.add(function (element){
    var GenericModelView = Backbone.View.extend({
        render: function(canvasLayer){
            var m = this.model,
                scale = canvasLayer.scale,
                w = m.get('width') * scale,
                h = m.get('height') * scale;

            canvasLayer.ctx.fillStyle = m.get('color');
            canvasLayer.ctx.fillRect(
                -(w / 2),
                -(h / 2),
                w,
                h
            );

            return this;
        }
    });
    return new GenericModelView({model:element });

}, plugins.validators.isBox);

More info on how Occamsrazor.js works are here.

I consider this experiment a step in the right direction.
Soon I'll try to make further steps.