Home » Javascript » how to make html canvas undo and redo function?

how to make html canvas undo and redo function?

Posted by: admin August 19, 2018 Leave a comment


first of all, sorry for my poor english.
I have a trouble to make redo and undo function in my application.. i already had read other questions and answers but failed to apply to my project. The recent answer i tried to follow is this one.

my html code

<th><img src="images/undo.png" onclick="undoLastPoint()"></th>
<th><img src="images/redo.png" onclick="()"></th>

my javascript code

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var isDrawing=false;

function pencil () {

canvas.onmousedown = function(e) {
    var pos = getMousePos(canvas, e);
    isDrawing = true;
    ctx.moveTo(pos.x, pos.y);

canvas.onmousemove = function(e) {
    var pos = getMousePos(canvas, e);
    if (isDrawing) {
        ctx.lineTo(pos.x, pos.y);

canvas.onmouseup = function() {
    isDrawing = false;

function undoLastPoint() {

// remove the last drawn point from the drawing array
var lastPoint=points.pop();

// add the "undone" point to a separate redo array

// redraw all the remaining points

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top