I have a canvas HTML5 drawing pad.
I would like to create a button with an undo function.
How can I do it?
My idea was to have one array stack. Anytime you draw and release the mouse, it saves the canvas image to the undo array stack by push. But as I tried it, it doesn't really work... Is there a better idea?
Thank you in advance!
var canvas = document.getElementById('paint');
var ctx = canvas.getContext('2d');
var sketch = document.getElementById('sketch');
var sketch_style = getComputedStyle(sketch);
var mouse = {x: 0, y: 0};
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = "red";
function getColor(colour){ctx.strokeStyle = colour;}
function getSize(size){ctx.lineWidth = size;}
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};