The data object stored in a state can be more than a string. Custom JavaScript objects and even some native types such as ImageData can also be used. The data provided is saved using the structured clone algorithm, which preserves complex relationships such as cycles and multiple references to the same object. This makes saving and restoring even complex objects a breeze as illustrated in this simple demo. In the demo, snapshots of a canvas are captured to create an undo stack using code like the following:
To change this to keep track of the current state without tracking each change, you can use replaceState instead of pushState.
function init() {
/* ... */
// Handle page load and reload
loadState();
// Listen for history navigations (e.g. the back button)
window.addEventListener("popstate", loadState, false);
}
/* ... */
function stopDrawing() {
// Take a snapshot of the current state as an ImageData instance
var state = context.getImageData(0, 0, canvas.width, canvas.height);
history.pushState(state, "");
/* ... */
}
function loadState() {
// Grab the data for the current state so we can restore it
var state = history.state;
/* ... */
if (state) {
// Restore the canvas to our saved ImageData state
context.putImageData(state, 0, 0);
}
}
Комментариев нет:
Отправить комментарий