JS/HTML5-用数组中的图像数据重新绘制画布

JS/HTML5 - Redraw canvas with image data from an array

本文关键字:新绘制 绘制 数据 HTML5- 数组 图像 JS      更新时间:2023-09-26

我正在尝试为画布实现一个撤消函数。基本上,人们可以在画布上画画,然后将其恢复到以前的状态。这就是理论。每次调用函数绘图时,我都会保存当前的imageData。它保存在一个数组eD(命名空间).history.绘图工作得很好,即使我操作imageData。这是我的draw函数(cD也是一个命名空间):

editorClass.prototype.draw = function(){
    eD.history.push(cD.imageData);
    cD.context.putImageData(cD.imageData, 0, 0);
}

现在,如果我试图撤消其间所做的更改,我会使用一个名为undo的函数,它看起来像:

editorClass.prototype.undo = function(){
    var temp = eD.history.pop();
    cD.context.createImageData(cD.width,cD.height); //Can leave this out, nothing changes
    cD.context.putImageData(temp, 0, 0);
}

如上所述,这是行不通的。我使用的画布是在用户加载网站后创建的。cD.imageData源自此函数:

editorClass.prototype.getPixels = function(){
    cD.imageData = cD.context.getImageData(0, 0, cD.width, cD.height);
    // get the image data of the context and save them into namespace
    cD.pixels = cD.imageData.data;
    // get the pixels
    cD.pixelsLength = cD.width * cD.height * 4;
    // precompute the length of the pixel array
}

如果需要,这两个名称空间都是可见的。由于我对画布还很陌生,这可能是一个简单的问题——所以如果你有改进:我是一个空桶,填充我;)

感谢

在没有看到所有代码的情况下,我不确定您的代码不起作用的确切原因,但我怀疑这是因为只尝试使用像素阵列而不是图像数据对象执行putImageData

这是我写的一个演示,工作

实时演示

这是相关的代码

var savedData = [];   
undoButt.addEventListener("click", function () {
    // as long as there is data put it onto the canvas.
    if (savedData.length > 0) {
        var imgData = savedData.pop();
        drawCtx.putImageData(imgData, 0, 0);
    }
});
drawCanvas.addEventListener("mousedown", function (e) {
    // push the current state
    var imgData = drawCtx.getImageData(0, 0, drawCanvas.width, drawCanvas.height);
    savedData.push(imgData);
});

这和你用过的概念一样,似乎还可以。