Skip to content Skip to sidebar Skip to footer

Html5 Canvas Drawing History

I'm curious to know how applications such as Adobe Photoshop implement their drawing history with the ability to go back or undo strokes on rasterized graphics without having to re

Solution 1:

I may have a solution.....

var ctx = document.getElementById("canvasId").getContext("2d");
varDrawnSaves = newArray();
varUndo = newArray();
varFigureNumber = 0;
var deletingTimer;
functiondrawLine(startX, startY, destX, destY) {
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(destX, destY);
    ctx.stroke();
    varPara = newArray();
    Para["type"] = "line";
    Para["fromX"] = startX;
    Para["fromY"] = startY;
    Para["toX"] = destX;
    Para["toY"] = destY;
    DrawnSaves.push(Para);
    FigureNumber++;
}
functionundo() {
    ctx.beginPath();
    ctx.clearRect(0, 0, 500, 500);
    Undo[FigureNumber] = DrawnSaves[FigureNumber];
    DrawnSaves[FigureNumber] = "deleted";
    FigureNumber--;
    drawEverything();
    startTimeoutOfDeleting();
}
functionundoTheUndo() {
    FigureNumber++;
    DrawnSaves[FigureNumber] = Undo[FigureNumber];
    drawEverything();
    clearTimeout(deletingTimer);
}
functiondrawEverything() {
    for (i = 0; i < DrawnSaves.length; i++) {
       if (DrawnSaves[i].type == "line") {
          ctx.beginPath();
          ctx.moveTo(DrawnSaves[i].fromX, DrawnSaves[i].fromY);
          ctx.lineTo(DrawnSaves[i].toX, DrawnSaves[i].toY);
          ctx.stroke();
       }
    }
}
functionstartTimeoutOfDeleting() {
   setTimeout(function() {Undo[FigureNumber] = "deleted";}, 5000);
}

This is really simple, first I draw a line when the function is called and save all his parameters in an array. Then , in the undo function I just start a timer do delete the figure drawn i 2000 miliseconds, clears the whole canvas and makes it can't be redrawn. in the undoTheUndo function, it stops the timer to delete the figure and makes that the figure can be redrawn. In the drawEverything function, it draws everything in the array based on it's type ("line here"). That's it... :-) Here is an example working : This, after 2sec UNDOs then after 1sec UNDOTHEUNDO

Post a Comment for "Html5 Canvas Drawing History"