删除上一个笔画(创建一个临时行) - Javascript / HTML5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16431140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:39:13  来源:igfitidea点击:

Remove a previous stroke (make a temporary line) - Javascript / HTML5

javascriptjqueryhtmlcanvasjquery-events

提问by Funkyguy

I am trying to make a simple paint application and I want the lines to sort of preview the line after you specify a lines start point. The corresponding Javascript is like this:

我正在尝试制作一个简单的绘画应用程序,并且我希望线条在您指定线条起点后对线条进行排序。对应的Javascript是这样的:

var Edges = new Array();
var Vertecies = new Array();
var Mouse = {x:0, y:0}


function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function addEdge() {
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");

    var i=0;
    var Start = { x:0, y:0}
    var End = { x:0, y:0}
    var Line = (Start, End);
    var temp = new Array();
    $("#myCanvas").mousemove(function(e){
        console.log("mouse is movin!");
        if(i==1)
        {
          var pos = findPos(this);
          console.log("I = 1 AHHHH")
          ctx.moveTo(Start.x, Start.y);
          ctx.lineTo(e.clientX-pos.x, e.clientY-pos.y);

          ctx.stroke();

        }
        else{

        }
    })


    $("#myCanvas").click(function(event){
        var pos = findPos(this);
        var x = event.pageX - pos.x;
        var y = event.pageY - pos.y;
        if (i==0)
        {
            Start = {x:x,y:y}
            i++;
        }
        else if(i==1) {
            End = {x:x,y:y}
            ctx.moveTo(Start.x , Start.y);
            ctx.lineTo(End.x , End.y);
            ctx.stroke();
            Line = (Start, End);
            Edges.push(Line);
            i++;
        }

        while(i==2) {
            Start = {x:0, y:0};
            End = {x:0, y:0};
            i=0;
        }
    });
};  

Apart from that, I have a related canvas called myCanvas.

除此之外,我有一个名为 myCanvas 的相关画布。

Basically what it does is it makes lines going from that point to my cursor until I click again, then it will stop and now I'm left with just this mound of lines.

基本上它的作用是让线条从那个点到我的光标,直到我再次点击,然后它会停止,现在我只剩下这一堆线条。

How can I get a "temporary" line after I've clicked once going from that clicked location to my cursor and then place a permanent line where my second click is.

从单击的位置到我的光标单击一次后,如何获得“临时”行,然后在第二次单击的位置放置一条永久行。

采纳答案by markE

You were very close with your code. Here's some adjustments that fill in the gaps.

你非常接近你的代码。以下是一些填补空白的调整。

[Edited to show a single canvas solution]

[编辑以显示单个画布解决方案]

To avoid drawing “a mound of lines” when the user drags their new line, you mustclear the canvas during each mousemove and draw just their latest dragging line.

为避免在用户拖动新线时绘制“一堆线”,您必须在每次鼠标移动期间清除画布并仅绘制他们最新的拖动线。

Clearing the canvas will also clear any lines previously drawn by the user, so you must redraw the previous lines with every drag. To do that, you must store enough info about each line to redraw it.

清除画布也将清除用户先前绘制的所有线条,因此您必须在每次拖动时重新绘制先前的线条。为此,您必须存储有关每条线的足够信息以重新绘制它。

For each line you will need the starting and ending points (x1/y1 and x2/y2). You can put these starting and ending points in an object and store the line-objects in an array:

对于每条线,您将需要起点和终点(x1/y1 和 x2/y2)。您可以将这些起点和终点放在一个对象中,并将线对象存储在一个数组中:

// an array to store previous lines
var storedLines=[];

// to store a new line
storedLines.push( { x1:10, y1:20, x2:50, y2:35 } );

This function redraws all the previously drawn lines

此函数重绘所有先前绘制的线条

    function redrawStoredLines(){

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

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

        // redraw each stored line
        for(var i=0;i<storedLines.length;i++){
            ctx.beginPath();
            ctx.moveTo(storedLines[i].x1,storedLines[i].y1);
            ctx.lineTo(storedLines[i].x2,storedLines[i].y2);
            ctx.stroke();
        }
    }

Now displaying the user's dragging line is much easier like this:

现在显示用户的拖动线要容易得多,如下所示:

function handleMouseMove(e){

  if(!isDown){ return; }

  redrawStoredLines();

  var mouseX=parseInt(e.clientX-offsetX);
  var mouseY=parseInt(e.clientY-offsetY);

  // draw the current line
  ctx.beginPath();
  ctx.moveTo(startX,startY);
  ctx.lineTo(mouseX,mouseY);
  ctx.stroke()

}

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/NnZ7a/

这是代码和小提琴:http: //jsfiddle.net/m1erickson/NnZ7a/

<!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>

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

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var storedLines=[];
    var startX=0;
    var startY=0;
    var isDown;

    ctx.strokeStyle="orange";
    ctx.lineWidth=3;

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

    $("#clear").click(function(){ storedLines.length=0; redrawStoredLines(); });

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

      isDown=true;
      startX=mouseX;
      startY=mouseY;

    }

    function handleMouseMove(e){

      if(!isDown){ return; }

      redrawStoredLines();

      var mouseX=parseInt(e.clientX-offsetX);
      var mouseY=parseInt(e.clientY-offsetY);

      // draw the current line
      ctx.beginPath();
      ctx.moveTo(startX,startY);
      ctx.lineTo(mouseX,mouseY);
      ctx.stroke()

    }


    function handleMouseUp(e){

      isDown=false;

      var mouseX=parseInt(e.clientX-offsetX);
      var mouseY=parseInt(e.clientY-offsetY);

      storedLines.push({x1:startX, y1:startY, x2:mouseX, y2:mouseY});

      redrawStoredLines();

    }


    function redrawStoredLines(){

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

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

        // redraw each stored line
        for(var i=0;i<storedLines.length;i++){
            ctx.beginPath();
            ctx.moveTo(storedLines[i].x1,storedLines[i].y1);
            ctx.lineTo(storedLines[i].x2,storedLines[i].y2);
            ctx.stroke();
        }
    }

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

</head>

<body>
    <p>Drag to draw lines</p>
    <canvas id="canvas" width=300 height=300></canvas><br/>
    <button id="clear">Clear Canvas</button>
</body>
</html>