[英]undo on canvas is not working correctly
I am trying to add undo functionality in canvas. 我正在尝试在画布中添加撤消功能。 But it is not working correctly. 但是它不能正常工作。
Issue - 问题 -
Let say i have drawn 3 line separately on canvas, but when i have start doing undo on it , 假设我在画布上分别绘制了3条线,但是当我开始对其进行撤消操作时,
2nd click - it shows 2 lines 第二次单击-它显示2行
3rd click - it show 1 line 第三次单击-它显示1行
When i start to draw again on canvas, all lines redrawn ie, all three lines redrawn 当我再次开始在画布上绘制时,所有线条均重新绘制,即所有三行都重新绘制
Please check this fiddle and draw on it 请检查这个小提琴并在上面画画
My code below 我的代码如下
HTML 的HTML
<canvas id="c" width="500" height="300"></canvas> <input type='button' onClick='undoDrawOnCanvas();' id='btnUndo' value='Undo drawing'>
CSS 的CSS
canvas { border: 1px solid #ccc }
JS 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();
}
}
I've added beginPath()
to the onmousedown
event. 我已经将beginPath()
添加到onmousedown
事件中。
Maybe the updated code in this fiddle is what you are looking for: 也许此小提琴中的更新代码是您想要的:
https://jsfiddle.net/dc67eaop/4/ https://jsfiddle.net/dc67eaop/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.