我正在尝试为画布实现撤消功能。基本上人们可以在画布上绘画,然后将其恢复到以前的状态。这就是理论。 每次调用函数绘制时,我都会保存当前的imageData。它保存在数组eD(名称空间).history中。即使我操作imageData,绘图也能正常工作。这是我的绘图功能(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
}
如果需要,两个名称空间都是可见的。由于我对画布很陌生,这可能是一个简单的问题 - 所以如果你有改进:我是一个空洞的人,请填补我;)
由于
答案 0 :(得分:3)
在没有看到所有代码的情况下,我不确定为什么你的代码不起作用,但我怀疑它只是试图用像素数组而不是图像数据对象做putImageData
。
这是我写的一个有效的演示
<强> Live Demo 强>
这是相关的代码
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);
});
它与您使用的概念相同,似乎工作正常。