Javascript 撤消重做中的逻辑错误
嘿,伙计们,我已经被这个问题困扰了两天了。 我似乎无法让这段代码正常工作: 画3个点,点击撤销2次,它做了它应该做的,所以我希望它不会太多修复。 我将“撤消-重做”绑定到两个按钮“撤消”和“重做”,它们在这里: -更新,这可能更有意义? 我让它工作,但现在它删除了两个,然后它通常会一个接一个Javascript 撤消重做中的逻辑错误,javascript,jquery,canvas,Javascript,Jquery,Canvas,嘿,伙计们,我已经被这个问题困扰了两天了。 我似乎无法让这段代码正常工作: 画3个点,点击撤销2次,它做了它应该做的,所以我希望它不会太多修复。 我将“撤消-重做”绑定到两个按钮“撤消”和“重做”,它们在这里: -更新,这可能更有意义? 我让它工作,但现在它删除了两个,然后它通常会一个接一个 function clearCanvas() { ctx.clearRect(0,0,canvasWidth,canvasHeight); } Stack1 = new
function clearCanvas()
{
ctx.clearRect(0,0,canvasWidth,canvasHeight);
}
Stack1 = new Stack();
///////////////////
function Stack() {
var currentState = 0;
var maxStates = 10;
var stateArray = [];
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
stateArray.push(image);
this.add = function() {
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
stateArray.push(image);
currentState++;
}
this.undo = function () {
stateArray.pop();
currentState--;
clearCanvas();
var image = stateArray[curentState];
ctx.drawImage(image,0,0);
}
this.redo = function () {
alert("worry about later");
// if (stackIndex%stackSize == stackTop) return;
//clearCanvas();
//var tmpImg = new Image();
// tmpImg.src = drawStack[++stackIndex%stackSize];
// ctx.drawImage(tmpImg, 0, 0);
}
}
在您的站点上,stackSize变量未定义。上面粘贴的代码略有不同,在链接中,堆栈大小被传递到
函数堆栈(
。但是,您没有向构造函数传递任何大小,并且该值未定义。发生的情况是,在推送一个新堆栈之后,您立即递增当前状态,这意味着它当前指向一个空条目
然后你在撤销中减少它,这意味着它现在指向你刚才保存的当前一个-这就是你在屏幕上的时刻
因此,您在第一次单击“撤消”时不会看到任何更改,而只会看到下一次的更改
您需要做的是,当您开始绘制新内容(即鼠标按下事件)时,只需增加当前状态。这将表明下一个插槽将充满当前操作。当您单击“撤消”时,它将正常工作,因为现在它将返回到上一个状态
过程:
Init currentState = -1
StartDraw
currentState++
clear items in stack from this position to max
EndDraw
fill array at currentState
Undo
currentState--
if < 0 set = -1 and clear canvas
else update canvas
Redo
currentState++
if > array.length -1 exit
if >= max set = max -1 and rotate array
update canvas at currentState
Init currentState=-1
StartDraw
当前状态++
将堆栈中的项目从此位置清除到最大值
收尾
在当前状态下填充数组
撤消
当前状态--
如果<0,则设置=-1并清除画布
其他更新画布
重做
当前状态++
如果>array.length-1退出
如果>=max set=max-1并旋转数组
在当前状态下更新画布
我已经用新代码更新了我的帖子,这可能更有意义?你能帮忙吗?this.undo=function(){if(currentState>0){currentState--;//stateArray.pop();clearCanvas();var image=stateArray[currentState];ctx.drawImage(image,0,0);}