Some time ago, I wrote a tutorial explaining
how to draw on a html5 canvas with the mouse, in this tutorial I will add a simple undo and redo functions to the canvas.
Live running example :
Line width : Color :
How it is done ?
To implement undo/redo feature for the canvas I decided to store a snapshot from the canvas (using the canvas’s toDataURL method) to an array "cPushArray", so each time the user draw or add something to the canvas the function cPush is called.
If cPush is called and the current position is not the last one, the array will be resized and all the following records will be deleted :
var cPushArray = new Array();
var cStep = -1;
var ctx;
// ctx = document.getElementById('myCanvas').getContext("2d");
function cPush() {
cStep++;
if (cStep < cPushArray.length) { cPushArray.length = cStep; }
cPushArray.push(document.getElementById('myCanvas').toDataURL());
}
When the user clicks the Undo button, the function cUndo will load and display the previous state using the drawImage method :
function cUndo() {
if (cStep > 0) {
cStep--;
var canvasPic = new Image();
canvasPic.src = cPushArray[cStep];
canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
}
}
When the user clicks the Redo button, the function cRedo will load and display the next available state in the cPushArray using the drawImage method :
function cRedo() {
if (cStep < cPushArray.length-1) {
cStep++;
var canvasPic = new Image();
canvasPic.src = cPushArray[cStep];
canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
}
}
This method is simple and straightforward, but if you are using an object-based canvas drawing you'll need a more complex approach to keep track of all the objects, positions, seizes ...
A full running sample and source code is available in the zip file attached to this article.
Happy coding and Feel free to make comments or ask questions.