S
S
Sergey Nozdrin2020-04-24 00:23:47
Canvas
Sergey Nozdrin, 2020-04-24 00:23:47

How to undo the last action when drawing on canvas with a pencil (pencil)?

Task:

  • create a canvas canvas with the ability to freely draw on it with a "pencil",
  • with the ability to completely cancel the drawn (cleaning the canvas)
  • with the ability to undo the last action (the last line drawn with a "pencil").


Completion status: partially completed. The canvas is created, the "pencil" works, the complete cleaning of the canvas works. I can't write a mechanism to undo the last "pencil" action of the last drawn curve.

Cause of failure: not enough data due to insufficient personal experience with canvas. Googling the TOP-30 also did not lead to an explicit answer.

Request: help and / or advice on solving the problem of undoing the last "pencil" action.

Plus, answering this question will fill a gap on the web for future developers.

The current JS code is:

if(window.addEventListener) {
    window.addEventListener('load', function () {
    
    var canvas, context, tool;
 
    function init () {
        // Находим canvas элемент
        canvas = document.getElementById('tablet');
        
        if (!canvas) {
            alert('Ошибка! Canvas элемент не найден!');
            return;
        }
 
        if (!canvas.getContext) {
            alert('Ошибка: canvas.getContext не существует!');
            return;
        }
 
        // Получаем 2D canvas context.
        context = canvas.getContext('2d');
        if (!context) {
            alert('Ошибка: getContext! не существует');
            return;
        }
        
        tool = new tool_pencil();
        canvas.addEventListener('mousedown', ev_canvas, false);
        canvas.addEventListener('mousemove', ev_canvas, false);
        canvas.addEventListener('mouseup',   ev_canvas, false);
    }
    
        // Очистка всего нарисованного на поле
        document.getElementById('clear').addEventListener('click', function() {
        context.clearRect(0, 0, tablet.width, tablet.height);
        }, false);
 
    // Здесь мы будем ловить движения мыши
    function tool_pencil () {
        var tool = this;
        this.started = false;
 
    
        this.mousedown = function (ev) {
            context.beginPath();
            context.moveTo(ev._x, ev._y);
            tool.started = true;
        };
 
        // Эта функция вызывается каждый раз, когда вы перемещаете мышь.
        // Но рисование происходит только когда вы удерживаете кнопку мыши
        // нажатой.
        this.mousemove = function (ev) {
            if (tool.started) {
                context.lineTo(ev._x, ev._y);
                context.stroke();
            }
        };
 
        // Событие при отпускании мыши
        this.mouseup = function (ev) {
            if (tool.started) {
                tool.mousemove(ev);
                tool.started = false;
            }
        };
    }
 
    // Эта функция определяет позицию курсора относительно холста
    function ev_canvas (ev) {
        if (ev.layerX || ev.layerX == 0) { // Firefox
            ev._x = ev.layerX;
            ev._y = ev.layerY;
        } else if (ev.offsetX || ev.offsetX == 0) { // Opera
            ev._x = ev.offsetX;
            ev._y = ev.offsetY;
        }
 
        // Вызываем обработчик события tool
        var func = tool[ev.type];
        if (func) {
            func(ev);
        }
    }
 
    init();
 
}, false); }


And the obvious tag in the HTML:

<canvas id = "tablet" width="1050" height="900"></canvas>
<button id="clear">Очистка всего холста</button>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
anikavoi, 2020-04-24
@light2041

Time for me to change my nickname to @Gooooogle :(
https://stackoverflow.com/questions/17150610/undo-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question