Saving and loading
By the end of this page you can store a board as JSON, load it back, and have it save itself to IndexedDB.
Export the board
viewport.exportJSON() returns the board as one JSON string: its elements, layers, active layer, camera and plugin state. Undo history is not included. exportState() returns the same data as a CanvasState object.
await fetch('/api/board', { method: 'PUT', body: viewport.exportJSON() });
Load a saved board
const saved = localStorage.getItem('board');
const viewport = new Viewport(document.getElementById('board')!, { tools: 'default' });
if (saved) viewport.loadJSON(saved);
loadJSON checks the data and upgrades boards saved by older versions of @fieldnotes/core. It throws on data it can’t read, including a board saved by a newer version, and leaves the current board as it was. Loading replaces the whole board and clears undo history.
loadState takes a CanvasState object and skips the check, so give it only state your own code exported.
Loading a board turns each arrow’s label into a text element on that arrow, with the id <arrow id>_label, so every client that loads the board creates the same element. Saves keep format version
6, so older versions of @fieldnotes/core can still load them.
The board below opens a saved board with two strokes and a note.
Save automatically
AutoSave saves the board 1000ms after the last change to its elements, layers or camera. Set debounceMs to change the wait.
const autoSave = new AutoSave(viewport.store, viewport.camera, {
key: 'board',
adapter: new IndexedDBAdapter(),
layerManager: viewport.layerManager,
});
const saved = await autoSave.load();
if (saved) viewport.loadState(saved);
autoSave.start();
- Without
adapter, it saves tolocalStoragethroughLocalStorageAdapter.IndexedDBAdapterstores the board in IndexedDB, for boards too large forlocalStorage.MemoryAdapterkeeps it in memory, for tests. - Pass
layerManager, or the saved board loses its layers. A board with plugins also passespluginStateManager: viewport.plugins, or plugin state is left out. load()checks the saved board asloadJSONdoes, so its result can go toloadState. When it can’t read the board, it returnsnull, passes the error toonErrorand saves nothing until a laterload()succeeds or you callclear(). That way a board written by a newer version is not overwritten.- Call
autoSave.stop()beforeviewport.destroy().