【问题标题】:Issue with saving canvas data to an array将画布数据保存到数组的问题
【发布时间】:2012-04-10 03:12:15
【问题描述】:

我正在使用 HTML5 画布创建一个 Web 应用程序来绘制图像(如绘制网络),我尝试实现“撤消”(ctrl+Z)和“重做”功能,在这里我遇到了一个奇怪的数组问题画布元素。 有时,当我按 ctrl+Z 撤消时,会出现一个空白图像,但是数据在数组中并且我指向正确的元素(因为当我使用撤消/重做时,我设法以正确的顺序获得正确的图像)。

如果你能看看下面的代码,我将不胜感激,我已经花了很多时间,但我无法找到问题... :-(

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);
    }
} 

任何解决方案或解决方法,我都会接受,非常感谢!!

【问题讨论】:

  • javascript 数组有 push、pop 和 shift。我不确定是否有理由进行所有模块化划分和索引...
  • 致对这篇文章感兴趣的人。我的代码有效,我只是忘记了著名的 img.onload 函数......这会导致我的应用程序中出现空白图片

标签: javascript jquery image html canvas


【解决方案1】:

我已经实现了几次撤消/重做功能,虽然由于许可原因我无法发布代码,但我可以给您一些伪代码,以展示撤消/重做实际上是多么简单:

首先,您需要两个数组。将这些称为“撤消”和“重做”。

每次状态更改时,将该状态推送到撤消堆栈。

当用户按下 ctrl-z(撤消)时,从撤消堆栈中弹出最后保存的状态。将此状态推送到重做队列,并使其成为当前状态。

当用户按下 ctrl-y(重做)时,从重做队列中弹出最后保存的状态。

如果任一数组开始填满超过您要保存的状态数,请使用 shift 丢弃最旧的状态。

有关 push、pop 和 shift 的参考,请参阅 MDN documentation。

另外,您可能会发现自己希望数组可以窥视,所以这里是:

Array.prototype.peek = function () {
    var theArray = this;
    var temp = theArray.pop();

    if (temp !== undefined) {
        theArray.push(temp);
    }

    return temp;
};

编辑:我的 sn-p 中有一个错误,在空数组上调用 .peek() 会推送未定义。

【讨论】:

  • 谢谢,听起来很棒,我会从头再来一次
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 2013-07-18
  • 2017-04-22
  • 2011-08-17
  • 2018-05-23
  • 2012-02-16
  • 1970-01-01
相关资源
最近更新 更多