繁体   English   中英

像在油漆中一样在画布上绘图

[英]Drawing to canvas like in paint

我有三个 arrys:

 clickX = [],
    clickY = [],
    clickDrag = [];

这是当您单击时发生的情况:

$('#canvasCursor').mousedown(function (e) {
    console.log('down');
    mouseX = e.pageX - this.offsetLeft;
    mouseY = e.pageY - this.offsetTop;
    paint = true;
    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
    redraw();
});

在这里,它将点击添加到数组并绘制。:

function redraw() { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // 清除画布

    ctx.strokeStyle = "green";
    ctx.lineJoin = "round";
    ctx.lineWidth = brushSize*2;

    for (var i = 0; i < clickX.length; i++) {
        ctx.beginPath();
        if (clickDrag[i] && i) {
            ctx.moveTo(clickX[i - 1], clickY[i - 1]);
        } else {
            ctx.moveTo(clickX[i] - 1, clickY[i]);
        }
        ctx.lineTo(clickX[i], clickY[i]);
        ctx.closePath();
        ctx.stroke();
    }
}

我现在正在尝试摆脱数组方式,因为当我使用滑块动态更改 var BrushSize 时,它​​会以新大小而不是当时的大小重新绘制整个图片。 我不知道如何保存数组中任何特定对象的大小,然后将它们分开绘制。

我不介意我是否不能实现这种方式给我的撤消功能,只要我能修复画笔大小的变化。 在这里你可以看到我在胡说八道! http://www.taffatech.com/Paint.html

-它似乎更慢,我猜是因为它是从数组中绘制的

编辑 :对不起,修正了一些拼写错误编辑2 :再次。 测试有点困难。

每次都没有理由重新绘制每个点。 您可以修改您的侦听器来执行此操作:

var prevMouseX=null,prevMouseY=null;
$('#canvasCursor').mousedown(function (e) {
    paint = true;

    console.log('down');
    //get current mouse coords
    mouseX = e.pageX - this.offsetLeft;
    mouseY = e.pageY - this.offsetTop;

    if (prevMouseX==null) {
        //store these coordinates for next time if they haven't been defined yet
        prevMouseX = mouseX;
        prevMouseY = mouseY;
    }
});

$('#canvasCursor').mousemove(function (e) {
    //get current mouse coords
    mouseX = e.pageX - this.offsetLeft;
    mouseY = e.pageY - this.offsetTop;

    if (prevMouseX==null) {
        //store these coordinates for next time if they haven't been defined yet
        prevMouseX = mouseX;
        prevMouseY = mouseY;
    }

    if (paint) {drawline(mouseX,mouseY,prevMouseX,prevMouseY);}

    //store these coordinates for next time
    prevMouseX = mouseX;
    prevMouseY = mouseY;
});

函数drawLine定义为:

function drawline(x1,y1,x2,y2) {
ctx.strokeStyle = "green";
    ctx.lineJoin = "round";
    ctx.lineWidth = brushSize*2;

    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.closePath();
    ctx.stroke();
}

不要将绘画存储到数组中
它严重减慢了绘图速度。 只需绘制最新的一行而不清除画布。 这样lineWeight更改不会影响到绘图之前。 所以删除ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); for循环。 您还可能希望仅在发生更改时更改上下文样式(lineWidth等),而不是每次运行redraw()函数时。

撤消支持
为每个鼠标按下会话制作不同的画布并将它们一起绘制,您可以轻松地进行撤消功能。 通过按下撤消,它只是将最新的画布拼接出画布阵列。 Google要了解有关绘制到临时画布的更多信息。

这是如何使用画布绘制像Paint

如果需要撤消功能,最佳选择是记录用户绘制的所有线段。

这是通过包含用户绘制的所有点(折线)的点阵列完成的。

要跟踪画笔大小和画笔颜色,您还需要在数组中包含此信息。

因此,数组的每个元素都将包含有关每个线段的信息:

  • x:此线段的结束x坐标
  • y:结束y坐标
  • 尺寸:画笔大小(lineWidth)
  • 颜色:画笔颜色(strokeStyle)
  • mode:“begin”表示新行的开头,“end”表示该行的结束。

它是如何工作的?

当用户拖动绘制线段时,每个mousemove事件都使用context.lineTocontext.stroke扩展当前段。

当用户选择新的BrushSize或BrushColor时,context.beginPath启动context.beginPath

当用户按下“撤消”按钮时,最后一个线段中的最后一个点将从点阵列中弹出。 然后重绘所有幸存的线段。 按住按钮时,撤销按钮每1/10秒触发一次。

这是代码和小提琴: 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>

我接受了这个问题,并用它来创建一个功能齐全的“着色书”解决方案,并将其发布在 Github 上。 https://github.com/collinph/jl-coloringbook

它处理所有鼠标问题 + 撤消和我们正在讨论的其他事情 + 可能出现的许多大小调整问题。 它确实将坐标存储在一个数组中,并且并不像某些人建议的那样慢——无论如何都不会在 Chrome 或 Safari 中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM