Last year I blogged about creating a recordable HTML5 Canvas. I explained how to record strokes/drawings created on a HTML5 Canvas and play them back. There are a couple of comments on that post asking me to explain how to save recordings and load them back. Serialization and deserialization of recordings was on my to-do list for a long time and finally this week I got around to implement it. There are different ways to serialize and deserialize recordings, and I have implemented a simple method – using JSON. The serialized data is a bit verbose because of descriptive variable names I have used, but you can change that easily.
RecordableDrawing (in this script file) function remains unchanged. I have added a new file drawingSerializer.js . Two important functions in this file are serializeDrawing and deserializeDrawing.
serializeDrawing takes a RecordableDrawing object as argument and returns JSON string containing array of recordings.
deserializeDrawing takes a String (serialized data) as argument and returns array of Recording objects.
To see how serialization and deserialization works, follow these steps –
- Click Record button and draw some strokes.
- Click Stop button when you are done
- Click Serialize button. This will display serialized text in a text area. You can copy the text and save somewhere. You could later deserialize the same text.
- Click Close button.
- Click Deserialize button. This will display the text area. Copy serialize text you had saved, if it is not already displayed in the text area
- Click Submit button. You will see that deserialized recording is played back in the Canvas.
I have reproduced serialized string of a drawing here, if you just want to see how deserialization works. Copy the text from the following text area. Click Deserialize button and paste the text in the new text area. Click Submit button.
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