JavaScript canvas画板,包含撤销和恢复功能的完整代码

发布时间:2023-05-05 17:38:04    发布者:文昌文城莱奥网络技术工作室    浏览次数:386

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Canvas画板</title>
  <style>
    canvas {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <button id="undo-btn">撤销</button>
  <button id="redo-btn">恢复</button>

  <script>
    // 初始化画板
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.lineWidth = 5;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    let isDrawing = false;
    let lastX, lastY;
    const undoStack = []; // 存储已绘制操作的栈
    const redoStack = []; // 存储已撤销操作的栈
    const undoBtn = document.getElementById('undo-btn');
    const redoBtn = document.getElementById('redo-btn');

    // 监听鼠标事件
    canvas.addEventListener('mousedown', e => {
      isDrawing = true;
      lastX = e.offsetX;
      lastY = e.offsetY;
    });
    canvas.addEventListener('mousemove', e => {
      if (!isDrawing) return;
      ctx.beginPath();
      ctx.moveTo(lastX, lastY);
      ctx.lineTo(e.offsetX, e.offsetY);
      ctx.stroke();
      lastX = e.offsetX;
      lastY = e.offsetY;
    });
    canvas.addEventListener('mouseup', () => {
      pushToUndoStack();
      isDrawing = false;
    });

    // 监听撤销和恢复按钮点击事件
    undoBtn.addEventListener('click', () => {
      const lastOperation = undoStack.pop();
      if (lastOperation) {
        redoStack.push(lastOperation);
        redraw();
      }
    });
    redoBtn.addEventListener('click', () => {
      const lastOperation = redoStack.pop();
      if (lastOperation) {
        undoStack.push(lastOperation);
        redraw();
      }
    });

    // 将绘制操作加入undoStack栈
    function pushToUndoStack() {
      undoStack.push(canvas.toDataURL());
      redoStack.length = 0;
    }

    // 重绘画布
    function redraw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      const img = new Image();
      const lastOperation = undoStack[undoStack.length - 1];
      img.src = lastOperation;
      img.onload = function() {
        ctx.drawImage(img, 0, 0);
      };
    }
  </script>
</body>
</html>