meltingice / CamanJS

Javascript HTML5 (Ca)nvas (Man)ipulation
http://camanjs.com
BSD 3-Clause "New" or "Revised" License
3.56k stars 406 forks source link

Undo/Redo functionality in CamanJS? #134

Closed splak closed 10 years ago

splak commented 10 years ago

Hi Im a newbie in camanjs.

I manipulate canvas with this code.

function vintage(id){
Caman(id, function(){

//I just added this code to reset the canvas to its original state
this.revert();
//----------------------------

this.vintage();
this.render();

});
} 

With the code this.revert(); , I can turn the canvas back to its original state. What if I use multiple effects and presets and just I want to revert the canvas few steps back to my last used effect?

meltingice commented 10 years ago

Due to memory constraints in JS, being able to revert step-by-step is something that hasn't been tackled yet.

If you want to revert the canvas a few steps back, you will need to revert to the original state and then execute all steps up to the state that you want.

vaibhavjaimini commented 6 years ago

one simple way to implement undo/redo with camanjs is to maintain a stack that store the canvas made in each step

var undoCanvasStack = [];
var redoCanvasStack = [];

function addToStack(){
var canvas = document.getElementById("target");
undoCanvasStack.push(canvas);
redoCanvasStack = [];
}

Caman('#target', function () {
this.vintage();
this.render(addToStack);
});

function undo(){
if(undoCanvasStack.length == 0)return;
var currentCanvas = undoCanvasStack.pop();
redoCanvasStack.push(currentCanvas);
var prevCanvas = undoCanvasStack[undoCanvasStack.length-1];
currentCanvas.parentNode.replaceChild(prevCanvas, currentCanvas);
}

function redo(){
if(redoCanvasStack.length == 0)return;
var currentCanvas = undoCanvasStack[undoCanvasStack.length-1];
var nextCanvas = redoCanvasStack.pop();
undoCanvasStack.push(nextCanvas);
currentCanvas.parentNode.replaceChild(nextCanvas, currentCanvas);
}