In this tutorial, we’ll build off the previous example and add history (also know as Storage & Playback), so our previous doodles are saved and displayed when the page is reloaded.
You’ll notice clear difference, besides the background color- in the new demo, you see previously drawn canvas, while the previous demo starts with a brand-new canvas.
Fetching Old Data using History (Storage & Playback) API
You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Portal. Once you have, clone the GitHub repository, and enter your unique PubNub keys on the PubNub initialization, for example:
You can easily retrieve last drawing data using
history() API. This function fetches historical messages of a channel. This Storage & Playback feature provides real-time access to a history for all messages published to PubNub.
To simply retrieve last 100 messages, this is all you need to do:
history() returns a list of up to 100 messages, the start time token and the ending time token. The response from
history() looks like:
[['message1', 'message2', 'message3',... ],'Start Time Token', 'End Time Token']
HTML5 Canvas: Blast from The Past
Let’s add this feature to your canvas app. With the API, make the app to automatically display the 50 previously drawn strokes on canvas. Before you start, you need to enable the feature on your admin dashboard (this is why you’ll first need to sign up for a PubNub account).
Once you call the history function, at the success call back, call the function
drawFromStream, created at the previous HTML5 canvas tutorial.
Boom. Now, at the initial load, you get old drawings from strangers! If you would like, the entire HTML5 canvas source code of the demo is on GitHub.