我试着撤消在画布上绘制的特定形状

时间:2014-01-24 07:09:03

标签: javascript html5 canvas

我正在尝试撤消在画布上绘制的选定形状。 以下是我正在实施的javascript代码     //线     功能线()     {         canvas = document.getElementById(“drawingCanvas”);         context = canvas.getContext(“2d”);         canvas.onmousedown = startLine;         canvas.onmouseup = drawLine;         canvas.onmouseout = stopLine;

};
function startLine(e) 
{
    isLine = true;
    context.beginPath();
    context.moveTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
}

function drawLine(e) 
{
    if (isLine==true) 
    {
        var x = e.pageX - canvas.offsetLeft;
        var y = e.pageY - canvas.offsetTop;
        context.lineTo(x ,y);
        context.stroke();
        context.closePath();
        cPush();

    }
}  
function stopLine()
{
    isLine = false;
}

//RECTANGLE

function rectangle() 
{
    canvas = document.getElementById("drawingCanvas");
    context = canvas.getContext("2d");
    canvas.onmousedown = startRectangle;
    canvas.onmouseup = drawRectangle;
    canvas.onmouseout = stopRectangle;
};

function startRectangle(e) 
{
    isRectangle = true;
    x = e.pageX - canvas.offsetLeft;
    y= e.pageY - canvas.offsetTop;  
    context.beginPath()
    context.moveTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);    
}
function drawRectangle(e) 
{
    if (isRectangle==true) 
    {
        a= e.pageX - canvas.offsetLeft;
        b= e.pageY - canvas.offsetTop;
        var k = Math.min(x,a);
        var l=Math.min(y, b);
        var width=Math.abs(x-a);
        var height=Math.abs(y-b);
        context.strokeRect(k, l, width, height );
        cPush();
    }
} 
function stopRectangle() 
{
    isRectangle = false;
}
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);}
    }
}

这里我使用鼠标事件绘制线条和矩形。我采用了带有线和矩形的dropdonw列表作为选项。 当我选择行时,只有行必须撤消,当我选择矩形时,只有矩形应该撤消,重做时也一样。 你能帮我解决一下如何撤消和重做选定的形状。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您无法撤消您在画布上绘制的任何内容。您只能重绘场景(或区域)。因此,要么清除整个画布并仅绘制应该留在那里的形状,要么只清除一个区域并恢复需要保留的内容。

我猜你应该保留在某些javascript结构(例如数组)中绘制的所有形状的坐标,以便您可以根据请求重绘所有内容。当某些内容被删除时 - 将其从结构中删除并重绘场景(区域)。