在介绍 undo redo 的实现之前。要先讲一下canvas的toDataURL()方法。
toDataURL()方法将canvas上所绘制的内容转换成格式png格式图片,并将图片通过base64编码。转换成形如如:data:image/png;base64,iVBORw0KGg.......的字符串,用来表示图片数据。
(PS:对此比較困惑的读者能够自行查找关于HTML
图片 BASE64 存储的相关问题,这个知识点还是非常重要的)
undo redo 的原理实际上非常easy。就是当每运行一次绘画,则将画板的内容转换成base64编码的字符串,存到缓存数组中去,然后在须要undo 的时候,将画板清空。再将缓存数组中的最后一次编辑的图片绘制到画板上就可以。相关的实现细节例如以下代码所看到的:
//undo redo
var history =new Array();
var cStep = -1;
/**
* put current canvas to cache
*/
function historyPush()
{
cStep++;
if (cStep < history.length)
{
history.length = cStep;
}
history.push($("#myCanvas").get(0).toDataURL());
}
/**
* function: undo
*/
function undo()
{
if (cStep >= 0)
{
cStep--;
var tempImage = new Image();
tempImage.src = history[cStep];
tempImage.onload = function () { ctx.drawImage(tempImage, 0, 0);};
}
}
/**
* function: redo
*/
function redo()
{
if (cStep
{
clearCanvas();
cStep++;
var tempImage = new Image();
tempImage.src = history[cStep];
tempImage.onload = function () { ctx.drawImage(tempImage, 0, 0); };
}
}