Posted on

Neural net-like canvas animation(2)

How to use html5 canvas to create animation that looks like neural net(part 2)

I took a little harder way to start, since I first introduced a node model, which is more complicated than simple line model. Here it is:


Line model is quite easy to grasp. It is a basic line between two nodes. Because all the movements are stored in Node model, it’s not required to do any other actions besides stoic animation, which only follows those two nodes. As a plus point – i don’t need to call init method.

But with the line accessing node’s pos attribute it is obvious we can’t move, because the attribute is updated only after the animation is complete. We have a few options, with 2 listed here:

  • use reference, so the pos attribute would be always the current one(or rather the next one) – preferred
  • update the values every time after iteration


Our first app.js script only works with one node. Now it should utilize two nodes and one line:

After you run it, you should see two points moving around while constantly being connected by line. Easy as that.


Let’s update our basic recommendations for models and add this:

  • Each animation should be stored as object. This object should have its own context(in terms of attributes).
  • Animation object should therefore consist of blueprint action(basically unique for each model so it could be stored inside of current model instead of another script) and function which prepares this action


Render method now utilizes disposableRenderActions. Since there could be time, when we need to queue more animations, but the old splice-to-dispose could broke the for renderActions cycle. With this, all of those finished animations should be removed at the end of render call. For simplicity, it is placed in Node model instead of Base model. If you are wondering about the ‘this.renderActions[i].iteration();’ part, check the code below.


Following my notes about models, each animation object should have its render part stored in actions attribute. With this, the model won’t be the one, that repaints the context. In the core, it should be the action of that model. According to new moveTo method, the rendering would be called through bind function. That gives more freedom while rendering, especially with attributes which belongs to animation object.

Animation object has two basic callable methods – iteration and finished. Accordig to previous code, call to finished method would dispose of associated animation right after current render method. As before, this occurs when animation reaches the iteration max counter.


With this, the Node model is prepared for another type of method – behavioral.

The point of this method is repeatedly calling some animation. It could be done like this, or it could be made into bigger moveTo method, which resets iteration count and sets a new positions. I wanted it to be separated so i picked the first one. The code above demonstrates how to do it BUT also demonstrates necessity to implement pseudo-asynchronous control flow, which i pointed out in the previous article in Base model(on and event methods).

The thing is, the repeated moveTo call would be disposed even before the increment call. It’s because the callback would be called before the render cycle ends, therefore the disposableRenderAction part would always remove the new animation instead of the old one.


On & Event mechanism is example of preventing such thing to happen, but also provides more flexibility in other areas. Please note, that for parallel animations it is still lacking something.


And finally app.js

This creates 40 nodes and for each 2 neighboring nodes additional one line. That means even first and last node.
Second example.

Posted on

Neural net-like canvas animation

How to use html5 canvas to create animation that looks like neural net

A few months ago i saw some animation, which you could see even in some movies – looks like neural network with all of these nodes and lines. I thought it would be nice to do it in html canvas. The whole net should be able to generate random movements and as a bonus, it should be able to react to mouse events(demo at the bottom)

For the gist of this idea, you can look at the following image, which serve as the basis

(*side note – i believe there is some lib on github which is doing the same and even better as a lib)


This example doesn’t use any third party lib, just vanilla javascript, so it could be added everywhere without dependencies.

As i planned the structure, i prepared one lib script, and three models for starters:

  1. Base model
  2. Node model
  3. Line model

Base model should contain basic functionality, which other models should inherit.
Node model stands for those dots which are points between lines – like joints.
And finally lines – between each two nodes, there is always line which connects them.


Let’s create html template:

There is nothing much to comment – just plain html template with style element and virtual paths to scripts.
I intend to use canvas element by getElementById and pass this element into my small lib. The lib itself should handle all around it. Manipulating and basic interaction with lib while initializing should be placed in app.js, which i cover later.


For now let’s create basic class for the lib.

I created basic class with attributes which are essetial(besides animationQueue – let’s ignore it for now).
This lib should accept any given object, which follows some interface(later covered in base model) through addObject method. I don’t want to link everything everywhere, so i am pushing only canvas context and basic color setting into every single new object.


Constructor doesn’t have any specialities, just accepts canvas element and initializes some arrays. Color would be later part of more robust default options, which could be altered by some other method.


Canvas as html element represents real painting canvas which could be seen everywhere – you pick some brush and paint some lines. When finished or not satisfied, just get the layer and throw it away. So you can’t just pick some object you painted and just alter it or remove it. Simply as that, the lib should provide other basic function renderCycle and clean for painting the whole layer and cleaning respectively. With models which gains reference to context, they could easily manage the rendering on their own. Lib just picks objects in cycle that should be rendered right away.


renderCycle should be called and then it should work on its own. That is guaranteed by the requestAnimationFrame part, which basically registers event, which should be fired before the whole browser repaints the scene(on browser level). This guarantees smoother framerate. Also the event is not eternal, that’s why the renderCycle is called again in the callback.


For better portability between browsers, you should consider using something like this:

var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;


Now lets create base model:

Because i want everything to be inherited, i don’t need to initialize anything in constructor. That means for attributes, that should be present in extended object, I had to create special method in prototype which only initializes those attributes. Next there is empty render method. Each and every different model should have it’s own render method, because logic ought to be different. Here I don’t need to specify anything, it works just as an interface in other languages that supports interfaces.

Also I prepared methods on & event which stands for on & emit for example in node.js events module. on registers callback that should be called when specified event is triggered. Additional arguments are just for convenience.


So here is the basic plan for models:

  • Each model should follow base model’s render function, which repeatedly, hopefully at 60fps(pc master race!) paints on canvas its part.
  • Model could have animations queues
  • When there is no more animations, the render function is still called. And because the canvas is always cleaned before each render cycle, the object should repaint its current position(let’s call this stoic repaint)
  • Animation should have its starting point and could have ending point. After animation, the current position has to be updated so next animation(even if stoic) uses this new position
  • Each animation could be just called from outside just once. Everything should be covered inside the model


Node model:

This is first version of node model. As a single model, it defines own attributes pos and nextPos(since this node should be moving in something like animations). Also it has defaults object which now consists only of value for maximum interations count – more iterations means longer animation. This node model has one animation method – moveTo. It creates anonymous function, which would be called in every iteration. After it ends, it should be disposed of by splicing the animation queue array.
This node model has already its render method in usable form with stoid rendering in case of empty queue.


So let’s create the app.js script which finally utilizes the lib:

After running the index.html you should be able to see the first animation which would differ each time you run it. Here is the first example.

I will cover more in the next article.


(images:, )

Posted on

My first html5 canvas game part2

This is the second part of my tutorial on building basic html5 canvas game (the firts part is here). Last time, we built some easy logic for spawning meteorits and their movement, control of ship and some collision events. Now we would like to add some counters for lives and points and some bonuses to make this game even more entertaining.

Continue reading My first html5 canvas game part2

Posted on

My first html5 canvas game part1

In this post, I would like to present you my first attempt to code a javascript game based on canvas. As my experiences with this technology are limited, I had to improvise a bit. My goal was to create a game where a triangle shaped spaceship under the control of player tries to avoid all the asteroids around and pick randomly generated bonuses.

Continue reading My first html5 canvas game part1