我试图在我的画布中实现撤消选项

时间:2014-01-13 06:28:35

标签: javascript css html5 canvas

我正在尝试在canvas中实现撤消和重做选项。我在我的程序中使用以下代码:

var cPushArray = new Array();
var cStep = -1;
function cPush()
{
    cStep++;
    if (cStep < cPushArray.length)
    {
        cPushArray.length = cStep;
    }
    cPushArray.push(document.getElementById("drawingCanvas").toDataURL());
}

function cUndo()
{
    if(cStep > 0)
    {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() { ctx.drawImage(canvasPic,0,0);}
    }
}
function cRedo()
{
    if(cStep < cPushArray.length-1)
    {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() {ctx.drawImage(canvasPic,0,0);}
    }
}

但是如果我调用cPush()方法,我无法在画布上绘制任何内容。 你可以告诉我上面的代码我错在哪里。

1 个答案:

答案 0 :(得分:1)

不要使用onload事件,因为它只是被DOM ready事件触发。

var canvasPic = new Image();
canvasPic.src = cPushArray[cStep];
//if ctx has get the context of canvas, draw the pic immediately
ctx.drawImage(canvasPic,0,0);