Reputation: 7214
I am creating a web application using HTML5 canvas to draw images ( like paint web ), I try to implement the "undo" (ctrl+Z) and "redo" features and here I am facing a strange problem with an array of canvas elements. Sometimes, when I hit ctrl+Z to undo, a blank image appears, however the data is in the array and I point to the correct element (because when I play with undo/redo I manage to have the corrects images in the right order).
If you can have a look at the following code I would be grateful, I've spent a lot of time already and I'm not able to locate the problem... :-(
function Stack(firstImg , size) {
var drawStack = new Array();
var stackIndex = 0;
var stackTop = 0;
var stackFloor = 0;
var stackSize = size;
drawStack[0] = firstImg;
this.add = function() {
drawStack[++stackIndex%stackSize] = cvs.toDataURL("image/png");
if (stackIndex >= stackSize) stackFloor = (stackIndex +1) % stackSize ;
stackTop = stackIndex % stackSize;
}
this.undo = function () {
if (stackIndex%stackSize == stackFloor ) return;
clearCanvas();
var tmpImg = new Image();
tmpImg.src = drawStack[--stackIndex%stackSize];
cvsCtx.drawImage(tmpImg, 0, 0);
}
this.redo = function () {
if (stackIndex%stackSize == stackTop) return;
clearCanvas();
var tmpImg = new Image();
tmpImg.src = drawStack[++stackIndex%stackSize];
cvsCtx.drawImage(tmpImg, 0, 0);
}
}
Any solution or workaround, I will take, thank you very much !!
Upvotes: 2
Views: 1901
Reputation: 46647
I have implemented undo/redo functionality a few times and, while I cannot post the code for licensing reasons, I can give you some psuedocode that should demonstrate how simple undo/redo actually is:
first, you need two arrays. call these "undo" and "redo".
Every time the state changes, push that state to the undo stack.
When the user presses ctrl-z (undo), pop the last saved state from the undo stack. push this state to the redo queue, and also make it the current state.
When the user presses ctrl-y (redo), pop the last saved state from the redo queue.
If either of the arrays begins to fill up past the # of states you want to save, use shift to discard the oldest state.
For references on push, pop, and shift, see the MDN documentation.
Also, you will probably find yourself wishing arrays had peek, so here it is:
Array.prototype.peek = function () {
var theArray = this;
var temp = theArray.pop();
if (temp !== undefined) {
theArray.push(temp);
}
return temp;
};
edit: there was a bug in my snippet, calling .peek() on an empty array would push undefined.
Upvotes: 6