How to defer or postpone execution of some Javascript code

— Just a small tip i’d like to share with you —

The issue :

Since Javascript is single threaded, during the execution of a piece of code :
• Changes to the DOM won’t show.
• Event handlers won’t trigger (mouse, keyboard, network, …).
• Drawings made on the canvas won’t show.
This can be annoying for a long computation, for which you’ll most probably want to see the ongoing progress, and also want the user to be able to cancel the operation.
You might also want to postpone / defer the execution of some code after every operation ended, if – for instance – you are sorting all your sorted list after every insertions/deletion operations occurred. No need to create a new (and most likely complex) control path, you just have to say ‘do this after you finished the rest’.

The common – and wrong -solution : setTimout.

A common way to solve this issue is to split your computation into smaller batches, and use a setTimeout(resumeCompute, 0) when one batch is done, to trigger the next execution while allowing the Browser to ‘breathe’, that is update the DOM and listen to events.

While seducing enough (and working), reading the specifications of setTimeout reminds us that we have no guaranty on when using a Zero delay setTimeout will trigger at once. Latest (late 2015) browsers will actually trigger the call 5 milliseconds later  (So yes 0 == 5, another javascript oddity :-) ), and depending on your software constraints, it might be a BIG issue (video games have a 16.6ms time frame, 5 ms is just too much).

The real solution : postMessage.

postMessage is meant to allow communication in between frames of the same web page. It is handled through the common event system, and thus a call to postMessage will act as triggering an event that will pile on the event queue, that, later, when the javascript engine finished its work, will be dispatched on any listener.
So you probably got the trick already : if we send a message to ourselves, we have a way to postpone / delay / defer the execution of whatever code after current call stack returned !!!

The code is very simple for a single task that you’d like to segment into chunks :

window.addEventListener('postMessage', resumeTheExecution);

Used with


But you might want some flexibility, so, by using the mighty new Map object, we can build a postpone function that will act even more simply as a 0 setTimeout call.
So the use will be like :


The code for postpone :

var postpone = (function () {
     var fnMap = new Map(), idMap = new Map(), fnId = 0;
     var msg = { fnId: 0 };
     function _postpone(fn) {
          if (!fnMap[fn]) {
                            fnMap[fn] = fnId;
                            idMap[fnId] = fn;
           msg.fnId = fnMap[fn];
           postMessage(msg, '*');
 function _postponeListener(e) {
     var fnId =;
     if (fnId) idMap[fnId]();
 window.addEventListener("message", _postponeListener);
 return _postpone;


I did a JSFiddle to check the 5 milliseconds issue, and in deed measures shows that a setTimeout doesn’t trigger at once on Firefox and Chrome.
I used the Monte Carlo method to compute PI, and this is quite a long job to get even a 10 digits precision : With postMessage, we can see the progress that gets drawn live on the canvas, and also stop the computation at any time by just pressing a key : way better than to wait in front of a frozen Browser.

Some Figures :
Time to compute 10.000 batches of 1000 point for the monte carlo method.
//  Display On
Chrome 46  :    postMessage : 22 seconds   setTimeout 76 seconds
Firefox 42   :     postMessage : 17 seconds   setTimeout 65 seconds
// Display Off
Chrome 46  :    postMessage : 1.3 seconds   setTimeout 55 seconds
Firefox 42   :     postMessage : 0.6 seconds   setTimeout 46 seconds

We can clearly see the overhead of setTimeout for each postponed call, which is around 5 ms, that obviously shows even more when processing time is shorter.

That’s quite all about this topic, hope you enjoyed the read, do comment if you want to !

Posted in Uncategorized | Leave a comment

An Intuitive Description of Runge-Kutta Integration

An Intuitive Description of Runge-Kutta Integration.

Posted in Uncategorized | Leave a comment

Painting with The HTML5 Canvas : A small presentation.

Painting with The HTML5 Canvas :A small presentation.

What is a Canvas ?

Think of your HTML5 canvas as a simple drawing surface that provides some powerful drawing tools. This canvas
might be used on an html page for immediate display, but also behind-the-scene to prepare some graphics for later use.
The drawing tools are provided through a Context, and most web Browsers offers two (exlusive) ways to draw
on a Canvas : WebGL and the Context2D.
WebGL is a very efficient but also very complex context, meant for demanding 2D or 3D graphics.
This presentation will focus on Context2D, a context meant for 2D drawing only, way simpler than webGL , and
powerful enough for most drawing tasks .
Boiler Plate Code to get a Context2D in Javascript :
In your Html file, add a canvas, give him a size (width, height), in pixels, and an id :

<canvas width=640 height=480 id='myCanvas'> </canvas >
// do not copy paste this html code but re-write it (issue with the < @gt; and html)

Then in your Javascript script, retrieve the HTML5 canvas element, and get its context2D with :

var myCanvas = document.getElementById('myCanvas');
var context = myCanvas.getContext('2d');

The drawing tools will either A) change the setting of the canvas or B) change the color value of some pixels : let’s
take a simple example and draw a red rectangle :

context.fillStyle = 'red'; // let's use red a filling color
context.fillRect(100, 100, 80, 40); // drawing a (red) rectangle starting at (100,100) sized (80, 40)

What a Canvas is NOT !

There’s a common misunderstanding of the canvas, especially from the ones having a strong Html background, that is
to see the canvas as a classical html container, just like, say, a
div, in which you would basically add/remove some
visual elements in pretty much the same way you do it in regular hmtl.
But this is completely wrong : when you draw, you actually only change the values of some pixels within your
graphic card, and that’s all. No ‘scene graph’ is built, meaning the canvas has no memory of what happened before : you
cannot query a previously inserted element to change it, remove it, make it draggable, or what-not.
Hence any logic that goes beyond drawing, must be done by yourself (or by an external library of course).
Rq : Those who likes to build scene as a way of drawing (building step-by-step some queriable objects) should have
a look either at an canvas helper library (createJS, fabricJS, … ) or have a look at the SVG format/Object.

Mind the current status

Using the Context2D is always done in two steps : you 1) first setup the (fill or stroke) color, the width of the line, the font when
dealing with text, and any paramaters then 2) you draw a figure.
When you draw (fill or stroke), the current settings values at that point of time will get applied.
Let’s look again at the red rectangle example, that we’ll visually improve a bit by adding a shadow :

context.fillStyle = 'red'; // let's use red a filling color
context.shadowColor = 'black'; // shadows will be black
context.shadowOffsetX = 10;
context.shadowOffsetY = 10; // shadow will be drawn (10,10) below the geometry
context.fillRect(100, 100, 80, 40); // drawing a (red and shadowed) rectangle starting at 100,100

You should notice here that the final draw call (fillRect) did not change : what did change is the status of the context by
the time of that call -here it is set to : red fill and black shadow.
Principle is that all the changes you make to your context are ‘sticky’ – remains active until you discard them – which is
why the Context2D is called a ‘state machine’ -a machine that internaly handle some state variables for you-.
!! it can lead to tricky bugs if you don’t keep this idea always close to your mind. !!
Now you may wonder how you’ll keep some order in your drawing code : what if i want to draw one thing with a shadow,
and another with no shadow ?
Hopefully we have a life-saver here, which is the save/restore principle : let’s see it in action :; // save all status variables here
context.fillStyle = 'red'; // let's use red a filling color
context.shadowColor = 'black'; // shadows will be black
context.shadowOffsetX = 10;
context.shadowOffsetY = 10; // shadow will be drawn (10,10) below the geometry
context.fillRect(100, 100, 80, 40); // drawing a (red and shadowed) rectangle starting at 100,100
context.restore(); // !!! restore all status variables as in the last save()

Here, after that code has run, we have a red shadowed rectangle drawn, and the current status of the context is exactly
what it was before (not red – no shadow).
Any time you wonder if a change you make to the context will affect other drawings you make, do
not wonder a second, and save (before) / restore (after), so you can be sure no specific settings will be applied on
other objects.

Two ways to draw

The Context2D offers two ways of drawing :
• Some drawing commands are immediate, meaning they will use the current status of the context to immediately
change the pixel colors . They are used for most common simple cases (see the above fillRect example).
• Some drawing commands are retained : they do not affect the pixels until you perform a stroke() or a fill(). They
are used in more complex cases, when drawing shapes built out of bezier curves, lines, …

Draw directly

The immediate commands of the Context2D are :
• fillRect / strokeRect : draws either the (filled) rect or just its outline.
• fillText / strokeText : draws either the text or just the text outline.
• clearRect : erase a part of the canvas.
• drawImage : used to draw an (or part of an) Image or canvas on current canvas.
• createImageData / getImageData / putImageData : (advanced) used to get/set the raw values of pixels.
• toDataURL : used to create an Image out of the Canvas.

Draw complex figures

The Context2D also offers some ‘retained’ commands that allows to draw more complex geometry. You can build
those geometry out of : lines, rect, arc (= part of circles), bezier curves, quadratic bezier curves, and arcTo.
The key thing to remember here is that you should always start a retained draw by beginPath, then build your
geometry step by step. Rq that nothing is drawn until you choose to stroke the outline or fill the whole geometry. You can
use closePath to automatcally link (by a line) the last point and the first point of the geometry.
You remember Context2D is a state machine, right ? So think of this way of drawing just like you woud do with a pen, which
‘remebers’ where it stands. Questions are : Where is the pen right now ? Where do i go from there ?
Here are the various retained commands of the Context2D :
• beginPath : start a new path. required for every new draw.
• closePath : Links the last built point to the first point by a line. Only if you need it.
• moveTo : unlift the pen, then set it at the provided point.
• lineTo : links last point to the provided point by a line.
• rect : adds a rect path to the current path. ! Rq that it does not draw immediatley like fillRect or strokeRect !
• arc : adds a (part of) circle to the current path.
• bezierCurveTo, quadraticCurveTo, arcTo : adds the corresponding mathematical curve to the path. All those curves
have a ‘smooth’ aspect.
A small example, a blue triangle :

context.beginPath(); // Start a new path ( == get rid of previous path)
context.moveTo( 80, 40 ); // move the pen at ( 80, 40)
context.lineTo( 140, 120 ); // line to (140, 120)
context.lineTo( 20, 120 ) ; // (horizontal) line to (20, 120 )
context.closePath(); // close the path --> line to (80, 40)
// notice nothing is drawn yet at that point
context.strokeStyle = '#FF6600' ; // stroke in red. Use a colorpicker to find the value you want.
context.lineWidth = 4 ; // use a 4 pixel width line
context.fillStyle = '#AAAAFF'; // fill in blue
context.fill(); // fill the current path (= the triangle)
context.stroke(); // stroke the triangle outline

Let’s fill those geometry nicely

You might stroke or fill with a single color, sure. To define a color, you have various ways :
• an html color string : ‘yellow’, ‘red’, …
• a rgb string : ‘rgb( 23, 150, 80)’
• a hsl string ‘hsl( 39, 75%, 75%)’ . Hsl is very handy to quickly create a coeherent palette.
• an hexa rgb string : ‘#FFE118’. This is the fastest way, if performances matters.
You can use a color picker (online or from your graphic editor) to find the right color.

BUT what about pouring even more colors ? The canvas provide two gradients for your viewing pleasure : a linear
gradient, and a radial one. To build a gradient, you must choose the part of the screen you’ll paint, then you define some
‘color stops’ : the color steps by which the gradient goes.

var grayFade = context.createLinearGradient(10,10,100,100); // create a gradient from (10,10) to (100,100)
grayFade.addColorStop(0 , 'rgb(100, 100, 100)'); // starting at drak gray
grayFade.addColorStop(0.3, 'rgb(180, 180, 180)'); // quickly becoming brighter
grayFade.addColorStop(1.0, 'rgb(255, 255, 255)'); // then fade to white
// in use :
context.fillStyle = grayFade;

BUT you can also use some kind of (simple) texturing, and have a pattern repeated with the createPattern method. Very usefull
to build a wall out of a brick photo. Notice that the pattern might be built out of a canvas, so you can build a small off-screen
canvas, draw one star on it with various colors on it, then create a pattern out of that canvas and fill the on-screen canvas with
that pattern !

Transform / Clip / Go Composite

Well now you drew some nice things using lines, bezier curves, and such, but you’d like to draw all this twice as big : how ?
Hopefully you have transforms just for that : you can translate, scale, rotate your context at any time to re-use some
drawing code in another way and do some nice effects. Mind that rotation angle is in radian, not degrees.
A small example :; // preserve the context
context.translate(canvas.width/2, canvas.height/2); // translate to the middle of the canvas
context.rotate( Math.PI / 3 ); // let's rotate a bit
context.scale(3, 3); // let's scale by a factor 3 (on both x and y)
context.fillStyle = 'red'; // let's use red a filling color
context.fillRect(0, 0, 40, 40); // drawing a (red) rectangle starting at (0,0) sized (40, 40)
// in fact, the rect will be drawn
// in the middle of the screen, rotated, and with a (120, 120) size
context.restore(); // restore context as before -no more transforms-

Another powerful feature is the globalCompositeOperation modes. They allow to change the way pixels are drawn, on a
per-pixel basis. You can use it for doing advanced masking with bitmaps. Use scenario are very specific, but they are very
quickly performed by most browsers. Notice that you can also define a blend mode, that will allow to do nice effects on colors
(the kind of effects high-end drawing software provide)
A scheme of the various composite modes is here :
It shows the output of drawing a new circle on an existing rect.

Last powerful feature is the clipping. You can define a part of the screen that will be the only part affected by all later drawings.
To define it, just create a path that defines the preserved area, and call clip ! Then do your drawings as usual.
You’ll most likely want to save/restore to avoid the clipping to remain permanent.
Small example :; // save context
context.beginPath(); // new Path
context.arc(50,50, 30, 0, 6.28 ); // circle at (50,50)
context.clip(); // now we are clipped
context.fillRect(50, 50, 30, 30); // draw a rect : it will have rounded borders


This page is useful for quick reference about Context2D methods / properties ::
Complete official reference for the Context2D : a bit harsh, but always true :
This is a long read, but this is a complete tutorial, very useful for graphic coding beginners
A quick cheat sheet for the Context2D :

Posted in Uncategorized | Tagged , , | Leave a comment

Javscript : A documentation pattern

documentation in Javascript

Javascript does not provide a built-in documentation tool : When one is searching for informations on how to use a class, a method or a property, he will have to dive into the code to find the relevant comments, which is time-consumming and might lead programmers to read the code rather than the documentation, thus favor implementation for specification and write code only compliant with the current version of the API. Another issue here is that if an API is provided minified, the documentation will be removed.

Another option is to use an online documentation site. Such documentation site can be generated automatically, with YUIDoc for instance. The issue here is that the help is not tied to the code, but rather an independant  web site.

A pattern for functions.

Let me suggest a pattern i found usefull, that allows :

– keep the code and its help together.
– easy to use.
– standard.
– resistant to minification.

This way you can provide help even with a minified version of your API, meaning you share the functionnality but not the code : your secrets are safe ( :-) ).
The idea is to take advantage of the lexical scope of a nammed function declaration, and that a function is an object to write.
Help is a string that is defined on the function object prior to its definition. This way you can read it when browsing the code.
But more importantly, you can have a description of the function in the console by typing .

One simple example :[
'print all the figures in the range ',
' arguments : start : starting figure (integer) ',
' end : ending figure (integer ) ',
' throws : invalidArgument exeception  ' ,
'   if start, end are not ordered integers. ' ].join('\n');

function printFigures(start, end) {
   // check arguments
   if ((start != ( 0 | start ) )
          ||(end != ( 0 | end ) )
             ||( start>end))
   throw ('printFigures invalidArgument : start and end must be two integers with start < end. (start :' + start + ' ; end :' + end + ' ).');
   // print figures
   for (var i=start; i<end; i++) {

Now if you type in the console :;

you’ll get :

print all the figures in the range
arguments : start : starting figure (integer)
end : ending figure (integer )
throws : invalidArgument execption if start, end are not ordered integers. 

The documentation pattern applied on Classes

For Classes, the pattern is a bit different : the class and class properties will
be explained in the Class function, and a little (simple) processing is needed to
hook the help on each methods :[
'Rect. Class. defines a colored rectangle. ',
' constructor arguments : ',
' left, top, width, height : numbers with obvious meaning.',
' color default to white.',
' properties : ',
' left, top, width, height, color : obvious meaning.',
' throws : no check performed.' ].join('\n');

function Rect(left, top, width, height, color) {
  this.left = left ; = top;
  this.width = width;
  this.height = height;
  this.color = color || '#FFF' ;

var rectPrototype = {
  drawHelp : [ 'draw : draws the rectangle on the provided context.',
               ' arguments : ctx is a valid Contxt2d ' ].join('\n'),
  draw : function (ctx ) { 
            ctx.fillStyle = this.color;
            ctx.fillRect(this.left,, this.width, this.height);
  isWithinHelp : [ 'isWithin : returns wether provided coordinates lies within the rect ',
                   ' arguments : x,y are coordinates of the point to test against' ].join('\n'),
  isWithin : function(x,y) {
               x -= this.left;
               y -=;
               return x >= 0 && x <= this.width && y >= 0 && y <= this.height ;

helpMerge(rectPrototype, Rect );

After writing this code, you can type in the console

to get :

Rect. Class. defines a colored rectangle.
constructor arguments :
left, top, width, height : numbers with obvious meaning.
color default to white.
properties :
left, top, width, height, color : obvious meaning.
throws : no check performed.

Just type to get the method help.
(most consoles (like FireBug) have autocomplete that will give you the list of all
just type : 

to get :

 isWithin : returns wether provided coordinates lies within the rect
arguments : x,y are coordinates of the point to test against

The code to merge a prototype description containing help with a
Class is this one :

 function helpMerge ( sourceObject, destinationClass ) {
    for (var prop in sourceObject) {
         var thisPropValue = sourceObject [prop] ;
         // skip help strings
         if (prop.match("Help$")) continue ; 
         destinationClass.prototype[prop] = sourceObject[prop];
         // method with help ? setup the help on the method, and add the method to the class function
         if ( (typeof (thisPropValue) == 'function') 
                    && (sourceObject[prop + 'Help']) ) {
         = sourceObject[prop + 'Help'];
                  destinationClass[prop] = thisPropValue ;


The proposal i make here is still uncomplete : for instance, properties defined on the prototype can’t provide
for any help.
But the main idea seems interesting : with this pattern, accessing the documentation of an API -even if
it was minified- is just as simple as typing in the console or No need to have the code,
no need to browse the code or an online documentation. The programming experience gets closer to the one we can have with
high level languages/editors.

Let me know if it triggers some thoughts, do not hesitate to comment, and happy coding !

Posted in Uncategorized | Tagged | 2 Comments

No more garbage : Pooling objects built with constructor functions – verbose version –

Why creating an object creates an issue.

We all know about the evil garbage collector of Javascript, a cruel monster that might at any moment freeze your game to recollect unused memory, and waste some frames or loose some inputs events, spoiling the game experience.
The fight against garbage creation must be led on several fronts : I’ll adress here the specific case of object creation using a constructor function, and in this article, i’ll present a way to recycle those object in a simple manner.

For those who likes to know the end of the movie before it starts : The simple and classical pattern i expose here leads to X2 to X5 performance boost, and reduces game freeze.

You can find the code of this article here : )

Objects Built with a constructor function

Using  a constructor function looks like :

var MyClass = function (param1, param2, ...) {
    this.prop  = param1;
    this.prop2 = param2;

MyClass.prototype.method1 = function(..) { ... };

var myObject = new MyClass(param1, param2, ...);

For the creation of myObject, the memory system is used three times :

  1. using the new operator is equivalent, in Javascript, to create a new object : {}, and assigning it to the ‘this’ of the constructor function.
  2. The constructor function (MyClass) will then perform intialisation and add some properties to the object. Memory will again be allocated for those properties.
  3. When the object is no longer in use (‘goes out of scope’), its memory it is not recollected at once : rather it is marked for recollection, hence feeding the evil garbage collector. When, at some random point in time, memory is lacking, a large amount of memory is reclaimed all at once : garbage collection occurs, freezing the game for up to 10ms – a disaster-.

Let us see a very simple example :

// in the init of the game...
var someBadGuy = new BadGuy() ;

// later on during a fight...
if ( Hero.strength > someBadGuy.strength ) {
   someBadGuy = new BadGuy(); //create a new enemy to fight against

Here, when we create a second bad guy after defeating the first one, we overwrite the reference to the first guy  (someBadGuy= new BadGuy()), so we have no more reference to the first guy : We created garbage.
Hence the first guy object is marked to be later recollected : this simple code is allready exhibiting a potential issue (in fact it created a performance issue in the future).

The performance hit due to object depends on two factors : the frequency of creation/disposal of objects, and the size of those objects.
Some sensitive cases might be :

  • Frantic games (no, i’m not talking about Super Crate Box :-) )
  • Games using a particle engine (for explosions, rainbows, …).
  • Games using 2D/3D physic engine(hence vectors computations).

But even in a slow-paced game, the recollection will randomly occur and make your character sometimes react oddly to, say, keystrokes, and hinder player’s experience.

Another thing worth noticing : Some (most?) game frameworks generates quite some garbage only to handle mouse moves or key strokes, and/or to handle object collisions, and/or use a class system that makes any class instance -even for simple classes- use quite some memory.
So before you even started to put some action, you can rest assured that the garbage collector will score in your game.
Still, this is not a reason to quit the fight.

The solution : let’s go to the pool

There is a much neater way to handle your objects : use a pool.

A pool is a stack of object that you put aside for your game :

  • When a new object is required, just take it from the pool then initialize it.
  • When you no longer use your object, throw it back in the pool.
  • If you need an object and the pool is empty, then -too bad- just use standard new() to get a new one.

So allocations happens less frequently, and recollection never happens (during the game).
Even better : if you determine the maximum number of objects your game might use, you can even pre-fill your pool with this number of objects, and you’ll never have to create or wait for recollection for this object.

How nice !

So how do we implement this in Javascript ?

Preliminary remark : I’ll make use here of ‘true’ Javascript ‘classes’,
i.e. classes :

  • setting properties in the constructor.
  • defining methods on the prototype.

This is the fastest and most memory efficient way to create objects in JS, and objects created this way also have the best performances.

Second remark : I won’t adress how to handle pooling with any of the many class library available for JS (like JQuery’s class system).

So here’s a (very simple) example of such a true JS class :

var BadGuy = function(posX, posY, gun, ammo) {
      this.posX   = posX  ;  this.posY   = posY  ;
      this.speedX = 10    ;  this.speedY = 0     ;
      this.gun    = gun   ;  this.ammo   = ammo  ;
      this.isAlive  = true  ;

BadGuy.prototype.move = function(dt) {
      this.posX += this.speedX * dt;
      this.posY += this.speedY * dt;

BadGuy.prototype.canShoot = function() {       
       return (this.ammo != 0);

(yes, very simple :-) )
And you use it with :

// create a new bad guy like this :
var myBadGuy = new BadGuy( 100, 10, 'AK47', 100);

// later on you can use it like this  :
if (myBadGuy.isAlive && myBadGuy.canShoot()) {
      Hero.runAwayShouting('please do not use your '
                                  + myBadGuy.gun +' on me !!');

So now let’s get back to pooling : the thing you have to change to a true JS constructor function to enable pooling is to handle a call with no arguments and make sure you setup your object just like a brand new one within the constructor :

var BadGuy = function(posX, posY, gun, ammo) {
      this.posX   = posX || 100 ;  
      this.posY   = posY || 0   ;
      this.speedX = 10    ;  this.speedY = 0        ;
      this.gun    = gun  || 'M16'   ;  
      this.ammo   = ammo || 100     ;
      this.alive  = true  ;
      return this;

This not a limitation, since even if you’re not pooling, handling undefined arguments :

  • Protect your function from calls to new() with a wrong number of arguments.
  • Ensures inner JS engine optimisations, since properties always have the same inner type (they never have the doomed ‘undefined’ value ).
  • It allows you to call the constructor with only the relevant parameters.

What you mustn’t do when pooling, though, is to add properties or methods on a created object, like with :

myBadGuy.isSmiling = true;

This, again,  is not a limitation, since late object change is a bad practice : it breaks inner optimisations of the JS engine (The JS engine creates a cached backing class for your object : this cache is broken if you change the object on the go).
– Simple solution for this : pour all the stuff you need in your object in the first place -.

So let us now create our pool :

BadGuy.pool = [];  // this one was hard.
(this code, as well as following code, has to be inserted
before the first object creation, but i don’t copy everything for clarity).

Now to get a new bad guy, we need another method that retrieves an object from the pool if one is available : pnew :

 BadGuy.pnew = function( posX, posY, gun, ammo) {
         var newGuy = null;
         // use the pool if object available... 
         if (this.pool.length >0) {
              newGuy = this.pool.pop();
          } else {
          // ... or create a new object if pool is empty.
              newGuy = new BadGuy();
         // initialize and return object.
         BadGuy.apply( newGuy, arguments );
         return newGuy;  

Use the pnew function like this :

var myBadGuy = BadGuy.pnew(100, 50, 'M4', 90);

Now, to dispose of the object, we also need a specific method that throws back the object on the pool : pdispose :

BadGuy.prototype.pdispose = function() {

Notice that this has to be set on the prototype (it is an instance we are disposing), while pnew is set on the creator function.
use the pdispose function like this :

if ( <= 0 ) {
     myBadGuy = null    ;

Notice that i set the myBadGuy var to null after disposal : this is to ensure we never reference twice the same object.
Here’s an example of what might occur if we do not pay attention :

var firstBadGuy = BadGuy.pnew(10); // get a guy, posX=10
firstBadGuy.pdispose();            // finally we don't need him...
                                   // ... but keep the reference..

var secondBadGuy = BadGuy.pnew(50); // get another guy posX=50 
                                    // It is taken from the 
                                    //  pool, and it is the latest
                                    // pushed, so === to firstGuy

// so now we have two references to the same object.
// if we do :
firstBadGuy.posX = 200 ; 
// we have for the second guy :
console.log( secondBadGuy.posX ); // --> output is 200, not 50 !!!

The issues that might be caused by multiple references might be a nightmare to detect and debug : each time you call pdispose(), ensure you don’t hold any reference to the disposed object.

So now, you must change all your new() calls to pnew(), and whenever an object is no longer in use, you must take care of pdisposing it and clearing any reference to it.

and then …

HURRA !!!!

At this point we have our pooling system, and the ugly garbage collector is defeated !!

or is he ?

Not quite, i am afraid : we have two concerns left.

Issue 1 : We still create some garbage.

When using push() and pop(), we do allocate/disallocate memory, so we still feed the monster with some crumb, so let us use an always-growing stack by handling the lenght separatly.  You’ll see how in the final code.

Issue 2 : what about re-use ?

We obviously need a way to avoid re-writing the same code for each pooled class.
Let us define a setupPool function on the prototype of the Function object, so that all functions call get pooled easily.

Object.defineProperty(Function.prototype,'setupPool', { value : setupPool });

function setupPool(initialPoolSize) {
	if (!initialPoolSize || !isFinite(initialPoolSize)) throw('setupPool takes a size > 0 as argument.');
    this.pool                = []          ;
    this.poolSize            = 0           ;
    this.pnew                = pnew        ;
    Object.defineProperty(this.prototype, 'pdispose', { value : pdispose } ) ; 
    // pre-fill the pool.
    while (initialPoolSize-- >0) { (new this()).pdispose(); }

function  pnew () {
    var pnewObj  = null     ; 
    if (this.poolSize !== 0 ) {              
// the pool contains objects : grab one
           this.poolSize--  ;
           pnewObj = this.pool[this.poolSize];
           this.pool[this.poolSize] = null   ; 
    } else {
// the pool is empty : create new object
           pnewObj = new this() ;             
    this.apply(pnewObj, arguments);           // initialize object
    return pnewObj;

function pdispose() {
    var thisCttr = this.constructor  ;
    if (this.dispose) this.dispose() ; // Call dispose if defined
    // throw the object back in the pool
    thisCttr.pool[thisCttr.poolSize++] = this ;   

A few comments on this code :

  1. As told earlier, i use an always-growing array/stack, so i handle its length separately in a poolSize property.
  2. I added here the possibility to pre-fill the pool, so no object creation occurs even within the first seconds of the game.
  3. I set, within the pool, to null the reference of the object we just grabbed to allow recollection in case it is not pdisposed afterwise, and just goes out of scope.
  4. In case you have some disposal work to do, just set a dispose() method on your object, it will get called when pdispose is called. One reason to do so might be that the object’s properties themselves are pooled.
  5. You might want to detect if you forget to pdispose some objects by counting all calls to pnew and to pdispose. At any moment you should have :
    activeObjectsCount == pnewCount  – (pdisposedCount – initialPoolSize)

Use setupPool like this :

// to create an instance :
  var myBadGuy = BadGuy.pnew(20,... );
// to dispose of it :

Reminder : the constructor function must handle undefined parameters and fully initialize the object.

So now victory is complete and all this was a very nice fight. Thank you for reading.

No ! Come On ! We want to know about the performance boost !

Ho, yes.


In fact this quite difficult to build a test that reflect an actual game sequence, where many object of different sizes have very different lifespan, and where ‘standard’ object ({}, [], strings, closures, functions, …) might be forgotten as garbage all along the way by many not-so-efficient game frameworks.
Another thing is that the performance measure won’t show us for how long the garbage collector froze the JS code during the tests. But i watched on FF/Chrome and we can see that garbage collection occurs often without pooling, and never when pooling (as expected).

Anyway i built a test in JSPerf that reflects *somehow* the performance gain you can expect from pooling.

So i consider that we have 4 different pooled objects, with different memory footprint (more realistic), and a given number of active object that i select randomly within those 4 classes.
We’ll create/dispose of them using three methods :

  • standard way : using new / relying on garbage collection.
  • using an empty-at-first pool.
  • using an pre-filled pool.

You can see the test and experiment by yourself at

I took 100 active objects, and 50000 of them will be created/disposed randomly.

Here is a screenshot of the results for :
Win8 Chrome / mac OS FF / win 8 IE10 / ipad Safari / mac OS Safari :

pooled vs non-pooled performance
pooled vs non-pooled performance

We can see that :

pre-filling the pool helps either a little or not at all.
Chrome sees a near X2 boost.
Firefox manages poorly memory, bust can be as fast as Chrome if helped : X5 boost.
IE10 gets a X3.3 boost.
The ipad appreciates the pre-fill, and gets a X2 boost.
Safari on mac OS, also enjoys pre-fill X2 boost.

Let me know if you experiment pooling in your game : i especially think here of games using intensively vector computation, where the speed boost should be tremendous.

I hope you enjoyed reading this article, and i wish you a good game.

Posted in Uncategorized | 1 Comment

Variable width lines in html5 canvas

varLineRoundedHi to all,

A quite simple topic today : how to draw a line that has a variable width, one that would look like one of those lines :


example of a line with variable width


example of rounded line with variable width

Those lines can be used to give more strength to a cartoonish drawing, or to draw more interesting lazer shoots, for instance.

1) Let us first look at the non-rounded case :

In fact drawing such a line is quite easy once we realize that what we need to draw is not a line : in fact it is a polygon.
If the line segment we want to draw is AB, the situation looks like this :


What we want to draw in fact is the A1,A2,B2,B1 polygon.

If we call N the normal vector (drawn on the scheme), and w1 and w2 the width in A and B respectively, we will have :
A1 = A + N * w1/2
A2 = A – N * w1/2
B1 = B + N * w2/2
B2 = B – N * w2/2

So how do we find this normal vector N ?
Maths says that if (x,y) defines a vector V , its normal vector coordinates are (-y, x).
N, the vector normal to AB will hence have ( – ( yB – yA ) ,  ( xB – xA ) ) as coordinates.
But there is an annoying thing about this vector : it depends on AB length, which is not
what we want : we need to normalize this vector, i.e. have it to a standard length of 1, so when we later multiply this vector by w1/2, we get the right length vector added.

Vector normalisation is done by dividing the x and y of the vector by the vector length.
Since the length is found using phytagore’s theorem, that makes 2 squares, one square root, and finally 2 divides to find the normalized vector N :

  // computing the normalized vector normal to AB
  length = Math.sqrt( sq (xB-xA) + sq (yB - yA) ) ;
  Nx     =  -  (yB - yA) / length ;
  Ny     =     (xB - xA) / length ;

So now that we can compute the four points, let us link them by a poly-line, and fill the resulting shape : here comes our variable width segment !

Here is the javascript code :

// varLine : draws a line from A(x1,y1) to B(x2,y2)
// that starts with a w1 width and ends with a w2 width.
// relies on fillStyle for its color.
// ctx is a valid canvas's context2d.
function varLine(ctx, x1, y1, x2, y2, w1, w2) {
    var dx = (x2 - x1);
    var dy = (y2 - y1);
    w1 /= 2;  w2 /= 2; // we only use w1/2 and w2/2 for computations.
    // length of the AB vector
    var length = Math.sqrt(sq(dx) + sq(dy));
    if (!length) return; // exit if zero length
    dx /= length ;    dy /= length ;
    var shiftx = - dy * w1   // compute AA1 vector's x
    var shifty =   dx * w1   // compute AA1 vector's y
    ctx.moveTo(x1 + shiftx, y1 + shifty);
    ctx.lineTo(x1 - shiftx, y1 - shifty); // draw A1A2
    shiftx =  - dy * w2 ;   // compute BB1 vector's x
    shifty =    dx * w2 ;   // compute BB1 vector's y
    ctx.lineTo(x2 - shiftx, y2 - shifty); // draw A2B1
    ctx.lineTo(x2 + shiftx, y2 + shifty); // draw B1B2
    ctx.closePath(); // draw B2A1

So let us see the result on a small example : drawing variable width segments within a circle with nice hsl colors :

Little sample of some variable width segments.

Little sample of some variable width segments.

2) Let us round things up.

We might want some round ending for our lines, ones just like the canvas allows us to draw by changing the line joins :

So now the scheme looks like this :


It is almost the same case as before, except that we’ll have to draw a half-circle from A1 to A2, and from B2 to B1.
To draw a circle in a canvas, you have to use arc. If you look how it works, you’ll see that it expects a start angle, and an end angle.
The start angle will be the angle between AA1 and the horizontal line, computed using the Math.atan2 function :

  var angle = Math.atan2( yA1 - yA, xA1 - xA);

Notice that javascript’s atan2 expects the y as the first argument, and x as the second.
The end angle is just the opposite of the start angle : it is equal to the start angle + PI.

So the javascript code is :

// varLineRounded : draws a line from A(x1,y1) to B(x2,y2)
// that starts with a w1 width and ends with a w2 width.
// relies on fillStyle for its color.
// ctx is a valid canvas's context2d.
function varLineRounded(ctx, x1, y1, x2, y2, w1, w2) {
    var dx = (x2 - x1),  shiftx = 0;
    var dy = (y2 - y1),  shifty = 0;
    w1 /= 2;   w2 /= 2; // we only use w1/2 and w2/2 for computations.    
    // length of the AB vector
    var length = Math.sqrt(sq(dx) + sq(dy));
    if (!length) return; // exit if zero length
    dx /= length ;    dy /= length ;
    shiftx = - dy * w1 ;  // compute AA1 vector's x
    shifty =   dx * w1 ;  // compute AA1 vector's y
    var angle = Math.atan2(shifty, shiftx);
    ctx.moveTo(x1 + shiftx, y1 + shifty);
    ctx.arc(x1,y1, w1, angle, angle+Math.PI); // draw A1A2
    shiftx =  - dy * w2 ;  // compute BB1 vector's x
    shifty =    dx * w2 ;  // compute BB1 vector's y
    ctx.lineTo(x2 - shiftx, y2 - shifty); // draw A2B1
    ctx.arc(x2,y2, w2, angle+Math.PI, angle); // draw A1A2    
    ctx.closePath(); // draw B2A1

Here’s another circle filled with rounded segments :


In fact i added some other functions to the canvas, i made a github containing all those helpfull functions that you might find here :

So that’s all, happy coding to you !

Posted in Uncategorized | Tagged , , , , , | Leave a comment

Introducing JSparkle, a versatile and fast Javascript Particle engine.


Explosions, fire, snow, blood, dust, shining stars, bonuses… particles are a handy tool to add nice effects to your games.
Every game object that is loosely related to the game logic (– eye candy –) should be handled as particle, since it allows to have very light weight objects, and it allows the game engine to focus on its real tasks.

Fireworks demo

The fireworks demo, running smoothly with 1800 particles.

JSparkle is a Particle engine that is quite simple to use : define what is a particle -it is a standard Javascript class  – what are its properties, how does it update, draw, and spawn – and then you’ll have access to some handy functions to spawn / autoSpawn / emit particles,  and also to test and monitor your engine.

JSparkle is fast, since the update phase does take very little time, and there’s nothing we can do to get the draw phase to run faster on an html5 canvas. It does not create garbage, since it uses a fixed loop buffer that allocates all particle on engine creation. Another few tricks here and there made the update time fell below 5% of the draw time on my computer.

I won’t go into a full review here of the engine and its features -it was quite an effort allready to have it work fast, commented, with a few (hopefully) clear examples… dig into the code (maybe only to read the methods comments) if you wish to know more.

The gitHub with the library and a few demos is here :

You’ll find some help if you want to create your own engine in the readme.txt, but maybe the fastest way to understand is to look at an example -bubbles being the most simple-. Feel free to play with the engine, and tell me what you think.

I’d be happy to include your examples, i’m sure some of you have cool graphical ideas that would just rock with JSparkle.

I post here a few screenshots and links to the demo. Obviously, the screenshots are … well… quite still :-) so watch the demos to know hat it’s like :-) .


Latest example is Fire. move your mouse !  :



Bubbles is a very-simple-on-purpose example where balls just bounce on the borders on the screen. It spawns once all particles on engine start.


Quite some bubbles.

StarField is what we would expect :


Starfield with 500 particles.

Here’s another starfield :
mouse your mouse around to change the stars direction.


Fireworks is the most amazing to date, be sure to click here and there to make your
own fireworks !!
Fireworks uses an auto-spawn, and spawn also on a mouse click.


(in this last screenshot we see the debug panel, that show the time and the current buffer use).

Posted in Uncategorized | Tagged , , , , | 5 Comments