我正在尝试在画布中添加撤消功能。但它无法正常工作。
问题 -
假设我在画布上分别绘制了3行,但是当我开始对其进行撤消时,
第二次点击 - 显示2行
第3次点击 - 显示1行
当我开始在画布上再次绘制时,所有行重新绘制,即重绘所有三行
请检查此fiddle并借鉴
我的代码
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();
}
}
答案 0 :(得分:0)