Category : Html | Author : Chtiwi Malek | First posted : 12/30/2012 | Updated : 4/10/2013
Tags : canvas, undo, redo, html5, tutorial, draw, erase, paint, rewind, code, script
Undo and Redo with HTML5 Canvas

Undo and Redo with HTML5 Canvas

Some time ago, I wrote a tutorial explaining how to draw on a html5 canvas with the mouse, in this tutorial I will add a simple undo and redo functions to the canvas.

Live running example :



  Line width : Color :       

How it is done ?

To implement undo/redo feature for the canvas I decided to store a snapshot from the canvas (using the canvas’s toDataURL method) to an array "cPushArray", so each time the user draw or add something to the canvas the function cPush is called.

If cPush is called and the current position is not the last one, the array will be resized and all the following records will be deleted :
var cPushArray = new Array();
var cStep = -1;
var ctx;
// ctx = document.getElementById('myCanvas').getContext("2d");
	
function cPush() {
    cStep++;
    if (cStep < cPushArray.length) { cPushArray.length = cStep; }
    cPushArray.push(document.getElementById('myCanvas').toDataURL());
}
When the user clicks the Undo button, the function cUndo will load and display the previous state using the drawImage method :
function cUndo() {
    if (cStep > 0) {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}
When the user clicks the Redo button, the function cRedo will load and display the next available state in the cPushArray using the drawImage method :
function cRedo() {
    if (cStep < cPushArray.length-1) {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}
This method is simple and straightforward, but if you are using an object-based canvas drawing you'll need a more complex approach to keep track of all the objects, positions, seizes ...

A full running sample and source code is available in the zip file attached to this article.

Happy coding and Feel free to make comments or ask questions.
About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.
Comments & Opinions :
RKJ
It works like charm. thank you very much.
- by RItesh on 2/1/2013
Create stand-along page for each code
Hi,
Wonderfull work. Thank you.
I have a suggestion if you can please add stand-along page for each code so people can visit that page see the example and copy the code with any extra stuff.

thanks

- by Ahmad Jamal on 11/8/2013
Nice Work
Hello,
Thanks for saving my time :)
Wonderful work...

Thanks.
- by Kinnari Shah on 11/12/2013
Interesting - seems to work on the web but not locally
It shows the picture and starts to draw after changing the src of jQuery to "http://..." but I get:

[Error] SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
    cPush (canvasdraw.js, line 66)
    (anonymous function) (canvasdraw.js, line 41)
    dispatch (jquery.min.js, line 3)
    i (jquery.min.js, line 3)

Whenever I draw something. Obviously it doesn't work then with UNDO.
- by silverdr on 9/2/2014
I got a same problem. In my case, because of loading index.html file in local diretory.
So I run that with simple server by expressjs. That's working.
- by yeojoy on 11/10/2014
Need more feature for this
Hi, this is rahul. i have integrated this to my application it is wirking fine, but along with this i need the support of drawing rectangle & line. Please if it possible share the source code to my mail. it is rahulshetty700@gmail.com
thanks in advance
- by rahul on 2/6/2015
Iteresting- undo Redo
Very Nice
- by Rajpal Chauhan on 8/25/2015
yiyui
tyuytu
tretrt
- by ty on 12/16/2015
Very good but I've problems
When I upload an Image on the background, I can draw good but i can't undo. cStep-- it's ok but the image not change.
Sorry for my english.
- by serra on 12/16/2015
Very good but I've problems
When I upload an Image on the background, I can draw good but i can't undo. cStep-- it's ok but the image not change.
Sorry for my english.
- by serra on 12/16/2015
Very nice explaination
Its seems to be really good but i needed html also is it possible to get it
- by prasanna on 2/6/2016
Background color and image
How to undo and redo background color and image of object in javascript
- by Rajeev Rahi on 3/31/2016
need more code
hi...i need code for eraser functionality...
- by Prajakta on 6/29/2016
Drawing an arrow
Thank you very much for the demo.
but i want also draw arrow and ellipse , can you help me with that ??
thank you very much for advanced
- by Dani on 10/4/2016
Web-developer and consultant
Thanks a lot! However in my project I had to generate canvas again before the back function worked because canvas is transparent!
- by Niki Ahlskog on 11/21/2016
mr
erasing is simple as u just take advantage of the white colour
- by kipsang on 3/13/2017
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :


» Member access