Working with Canvas and AngularJS

We finally managed to work with AngularJS and HTML5 Canvas together. Here below, I will share, briefly, our requirements and the approach we followed to achieve it.

The requirement was a bit tricky as we wanted to:

  1. Handle event handles on individual elements inside the canvas, and be able to add these elements dynamically based on the data in AngularJS

  2. Keep data for each individual element in AngularJS while using Canvas for only display of the data.

  3. Use controller inheritance for special handling of data in certain cases (for e.g. all the instances should be movable and draggable, but some instance may need to blink or show some color bands etc.)

To handle the operations on Canvas, we divided it into two parts:

  1. Canvas service

    It does the job of

    • initializing the canvas

    • adding or removing any element from the canvas

    • refreshing the canvas

  2. Instance directive and controller

    • the angular controller keeps the handle for the corresponding “canvas element”, and also all the data that is associated with it.

    • the event listeners on each element trigger specific functions in the angular controller which manipulate the instance data

    • the directive watches the instance data in controller, and correspondingly updates the canvas with the help of the canvas service

For controller inheritance, we found the following approach quite useful:
https://github.com/exratione/angularjs-controller-inheritance

This helped us create controllers dynamically, and with the help of instance directive, we could also handle individual updates on the canvas along with the generic event handling.

I understand that this approach may not be completely AngularJS-oriented, but it worked well for us, and we were able to handle a reasonable amount of interaction between AngularJS and HTML5 Canvas.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)