簡體   English   中英

在畫布上撤消無法正常工作

[英]undo on canvas is not working correctly

我正在嘗試在畫布中添加撤消功能。 但是它不能正常工作。

問題 -

假設我在畫布上分別繪制了3條線,但是當我開始對其進行撤消操作時,

第二次單擊-它顯示2行

第三次單擊-它顯示1行

當我再次開始在畫布上繪制時,所有線條均重新繪制,即所有三行都重新繪制

請檢查這個小提琴並在上面畫畫

我的代碼如下

的HTML

<canvas id="c" width="500" height="300"></canvas> <input type='button' onClick='undoDrawOnCanvas();' id='btnUndo' value='Undo drawing'>

的CSS

canvas { border: 1px solid #ccc }

JS

var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;
var restorePoints = [];

el.onmousedown = function(e) {
    isDrawing = true;
    ctx.lineWidth = 10;
    ctx.lineJoin = ctx.lineCap = 'round';
    ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function(e) {
    if (isDrawing) {
        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
    }
};
el.onmouseup = function() {
    isDrawing = false;
    saveRestorePoint();
};


function saveRestorePoint() {
    var oCanvas = document.getElementById("c");
    var imgSrc = oCanvas.toDataURL("image/png");
    restorePoints.push(imgSrc);
}


function undoDrawOnCanvas() {
    if (restorePoints.length > 0) {
       var oImg = new Image();
       oImg.onload = function() {
           ctx.clearRect(0, 0, el.width, el.height);            
           ctx.drawImage(oImg, 0, 0);
       }
       oImg.src = restorePoints.pop();
    }
}

我已經將beginPath()添加到onmousedown事件中。

也許此小提琴中的更新代碼是您想要的:

https://jsfiddle.net/dc67eaop/4/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM