by eidam

Canvas blackboard simple implementation

After reading a few chapters of the Canvassing ebook, I started to think intensively about how to create a basic canvas blackboard and how simply it is.


I will start with html and css code. I will leave this part without a comment:


That’s all.



Setting canvas blackboard object in javascript is a kind of necessity here. Lets go through it quickly:


Storing data

Okay, here starts the real problem – how to store the information about where ‘is painted’.  I was searching the web and found a lot of solutions and working examples. But in most cases it was about setting a new circle in the place of clicking or clicking + mousemoving. This was not sufficient because the geometry wasn’t continuous. Therefore I used lines geometries. For storing them I created an array of arrays “painted” that should look like

This means, we have two lines, first one with 2 points (with coordinates [1, 2] and [2, 1]), second one with 3 points.


Setting event listeners

Before setting listeners, we add one more global variable “drawing” (dafaultly set to false), that informs us whether we are creating geometries at that moment or not.

Now, we have to set 3 different event listeners:

  •  mousedown means, we have to turn storing data on and we also put new empty array to painted array (for initializing a new line):

  • mouseup will just set drawing to false:

  •  mousemove is then for adding a new point to our array (in case the drawing is set to true):


Rendering stored geometries

The last part is to fill the draw function, that will render our stored geometries to canvas. To draw a line we use this commands:

… and now put this lines in iteration of our painted array of array:


And now we are ready to draw on our canvas blackboard.

See the Pen Canvas blackboard by Eidam (@eidam61) on CodePen.