javascript - 使用 Canvas 撤消/重做绘画程序

标签 javascript jquery canvas

<分区>

我需要为我的绘画程序实现一个撤消/重做系统:http://www.taffatech.com/Paint.html

我想出的想法是有 2 个数组堆栈,一个用于撤消,一个用于重做。 每当您绘制并释放鼠标时,它都会通过推送将 Canvas 图像保存到撤消数组堆栈。如果你画别的东西然后释放它也会做同样的事情。但是,如果您单击撤消,它将弹出撤消数组的顶部图像并将其打印到 Canvas 上,然后将其插入重做堆栈。

单击时重做会自动弹出并按下以撤消。每次鼠标离开后都会打印撤消的顶部。

这是正确的方法还是有更好的方法?

最佳答案

一句警告!

将整个 Canvas 保存为图像以进行撤消/重做会占用大量内存并且会降低性能。

但是,您将用户的绘图逐步保存在数组中的想法仍然是一个好主意。

无需将整个 Canvas 保存为图像,只需创建一个点数组来记录用户在绘图时进行的每一次鼠标移动。这是您的“绘图数组”,可用于完全重绘您的 Canvas 。

只要用户拖动鼠标,他们就会创建一条多段线(一组相连的线段)。当用户拖动以创建一条线时,将该鼠标移动点保存到您的绘图数组并将其折线延伸到当前的鼠标移动位置。

function handleMouseMove(e) {

    // calc where the mouse is on the canvas
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // if the mouse is being dragged (mouse button is down)
    // then keep drawing a polyline to this new mouse position
    if (isMouseDown) {

        // extend the polyline
        ctx.lineTo(mouseX, mouseY);
        ctx.stroke();

        // save this x/y because we might be drawing from here
        // on the next mousemove
        lastX = mouseX;
        lastY = mouseY;

        // Command pattern stuff: Save the mouse position and 
        // the size/color of the brush to the "undo" array
        points.push({
            x: mouseX,
            y: mouseY,
            size: brushSize,
            color: brushColor,
            mode: "draw"
        });
    }
}

如果用户想要“撤消”,只需将绘图数组中的最后一个点弹出即可:

function undoLastPoint() {

    // remove the last drawn point from the drawing array
    var lastPoint=points.pop();

    // add the "undone" point to a separate redo array
    redoStack.unshift(lastPoint);

    // redraw all the remaining points
    redrawAll();
}

重做在逻辑上更棘手。

最简单的重做是用户只能在撤消后立即重做。将每个“撤消”点保存在单独的“重做”数组中。然后,如果用户想要重做,您只需将重做位添加回主数组即可。

复杂的是,如果您让用户在完成更多绘图后“重做”。

例如,您最终可能会得到一条有两条尾部的狗:一条新画的尾部和第二条“重做”的尾部!

因此,如果您允许在附加绘图后重做,则需要一种方法来防止用户在重做期间感到困惑。 Matt Greer 的“分层”重做的想法是一种好方法。只需通过保存重做点而不是整个 Canvas 图像来改变这个想法。然后用户可以打开/关闭重做以查看他们是否想保留他们的重做。

这是使用我为上一个问题创建的撤消数组的示例:Drawing to canvas like in paint

这是代码和 fiddle :http://jsfiddle.net/m1erickson/AEYYq/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="../excanvas.js"></script><![endif]-->

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var lastX;
    var lastY;
    var mouseX;
    var mouseY;
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var isMouseDown=false;
    var brushSize=20;
    var brushColor="#ff0000";
    var points=[];


    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // Put your mousedown stuff here
      ctx.beginPath();
      if(ctx.lineWidth!=brushSize){ctx.lineWidth=brushSize;}
      if(ctx.strokeStyle!=brushColor){ctx.strokeStyle=brushColor;}
      ctx.moveTo(mouseX,mouseY);
      points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"begin"});
      lastX=mouseX;
      lastY=mouseY;
      isMouseDown=true;
    }

    function handleMouseUp(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // Put your mouseup stuff here
      isMouseDown=false;
      points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"end"});
    }


    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // Put your mousemove stuff here
      if(isMouseDown){
          ctx.lineTo(mouseX,mouseY);
          ctx.stroke();     
          lastX=mouseX;
          lastY=mouseY;
          // command pattern stuff
          points.push({x:mouseX,y:mouseY,size:brushSize,color:brushColor,mode:"draw"});
      }
    }


    function redrawAll(){

        if(points.length==0){return;}

        ctx.clearRect(0,0,canvas.width,canvas.height);

        for(var i=0;i<points.length;i++){

          var pt=points[i];

          var begin=false;

          if(ctx.lineWidth!=pt.size){
              ctx.lineWidth=pt.size;
              begin=true;
          }
          if(ctx.strokeStyle!=pt.color){
              ctx.strokeStyle=pt.color;
              begin=true;
          }
          if(pt.mode=="begin" || begin){
              ctx.beginPath();
              ctx.moveTo(pt.x,pt.y);
          }
          ctx.lineTo(pt.x,pt.y);
          if(pt.mode=="end" || (i==points.length-1)){
              ctx.stroke();
          }
        }
        ctx.stroke();
    }

    function undoLast(){
        points.pop();
        redrawAll();
    }

    ctx.lineJoin = "round";
    ctx.fillStyle=brushColor;
    ctx.lineWidth=brushSize;

    $("#brush5").click(function(){ brushSize=5; });
    $("#brush10").click(function(){ brushSize=10; });
    // Important!  Brush colors must be defined in 6-digit hex format only
    $("#brushRed").click(function(){ brushColor="#ff0000"; });
    $("#brushBlue").click(function(){ brushColor="#0000ff"; });

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});

    // hold down the undo button to erase the last line segment
    var interval;
    $("#undo").mousedown(function() {
      interval = setInterval(undoLast, 100);
    }).mouseup(function() {
      clearInterval(interval);
    });


}); // end $(function(){});
</script>

</head>

<body>
    <p>Drag to draw. Use buttons to change lineWidth/color</p>
    <canvas id="canvas" width=300 height=300></canvas><br>
    <button id="undo">Hold this button down to Undo</button><br><br>
    <button id="brush5">5px Brush</button>
    <button id="brush10">10px Brush</button>
    <button id="brushRed">Red Brush</button>
    <button id="brushBlue">Blue Brush</button>
</body>
</html>

关于javascript - 使用 Canvas 撤消/重做绘画程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17150610/

相关文章:

javascript - 如何关闭字母按钮?

javascript - 帮助用新字符替换最后一次出现的字符

android - 在用户在 Canvas 上触摸的位置绘制一个圆圈

javascript - 确保当用户返回页面而不刷新时,由 javascript 更改的元素保持更改

jQuery append 问题顺序错误

javascript - 脚本延迟不起作用

android - Android Canvas 中的平滑非常慢的文本动画,SUBPIXEL_TEXT_FLAG 不起作用

javascript - 在 R Shiny 中将鼠标光标更改为手(指针)

javascript - 有没有办法在泛型 (<T>) 函数/类 (Typescript) 中获取泛型类型的名称?

php - JavaScript 与 MYSQL 之间的通信