A few months back I had created an application that recorded and played back drawings on HTML5 Canvas. For some time now I wanted to refactor the code in that application and create a reusable ‘component’ from it. Which is what I did this week.
Go ahead and try the demo first – Press ‘Record’ key below and then draw some strokes/lines in the box with the mouse (holding down left button). Once you are done, click Stop button. Click ‘Play’ button to play back the drawing you just drew. You can pause and resume too.
Interesting piece of code in this application is to record strokes. You would have observed that, when playing back the drawing, the component does not draw all strokes at once, but it plays them backs in the sequence you had drawn, maintaining the time line. To do this, I collect all the strokes that are drawn in a certain time interval (in this application, it is 100 millis) and create a linked list. Each collection (of strokes) in this linked list stores time elapsed from the start of the recording.
When playing back, I use time elapsed in the first collection to start drawing strokes. Each subsequent collection is drawn after the difference between time elapsed for that collection and the previous collection.
You can find all the code in this file. ‘RecordableDrawing’ is the object you would create by passing id of the canvas –
drawing = new RecordableDrawing("canvas1");
This object captures strokes and draws them. ‘Recording’ object handles time slotting each stroke and playing them back, as described above. ‘ActionsSet’ object contains collection of strokes and also time interval from the start of the recording.
See the updated version of code and example (with features to set stroke color and size) in my blog post Record and Playback Drawing in HTML5 Canvas – Part II