1

使用下面的代码,我可以在画布上用鼠标点画线。我需要检测绘图线何时完成一个形状并用一些颜色填充它。

<script language="javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var worksheetCanvas = $('#worksheet-canvas');

        var context = worksheetCanvas.get(0).getContext("2d");
        var clicked = false;
        // The array of stored lines
        var storedLines = [];

        // The object for the last stored line
        var storedLine = {};
        var mouse = {
            x: -1,
            y: -1
        }

        var parentOffset = $('#canvas-holder').parent().offset();
        worksheetCanvas.click(function (e) {
            clicked = true;

            mouse.x = e.pageX - parentOffset.left;
            mouse.y = e.pageY - parentOffset.top;

            context.moveTo(mouse.x, mouse.y);

            // Push last line to the stored lines

            if (clicked) {
                storedLines.push({
                    startX: storedLine.startX,
                    startY: storedLine.startY,
                    endX: mouse.x,
                    endY: mouse.y
                });

            }

            // set last line coordinates

            storedLine.startX = mouse.x;
            storedLine.startY = mouse.y;

            $(this).mousemove(function (k) {
                // clear the canvas

                context.clearRect(0, 0, 960, 500);
                context.beginPath();
                context.strokeStyle = "rgb(180,800,95)";

                // draw the stored lines

                for (var i = 0; i < storedLines.length; i++) {
                    var v = storedLines[i];
                    context.moveTo(v.startX, v.startY);
                    context.lineTo(v.endX, v.endY);
                    context.stroke();
                }
                context.moveTo(mouse.x, mouse.y);
                context.lineTo(k.pageX - parentOffset.left, k.pageY - parentOffset.top);
                context.stroke();


                context.closePath();


            })

        })

    });
</script>
</head>
<body>
 <div id="canvas-holder">

 <canvas id="worksheet-canvas" width="960" height="500" style="background:black;">

                    </canvas>

                </div>


</body>
</html>
4

2 回答 2

3

[海报澄清后编辑]

此代码将绘制/继续一条折线到用户接下来单击的位置。

如果用户在他们开始的绿色圆圈中单击返回,则多段线将被填充。

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

<!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; padding:10px; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    ctx.strokeStyle="orange";
    ctx.font = '12px Arial';

    $("#canvas").mousedown(function(e){handleMouseDown(e);});

    function handleMouseDown(e){
      canvasMouseX=parseInt(e.clientX-offsetX);
      canvasMouseY=parseInt(e.clientY-offsetY);

      // Put your mousedown stuff here
      if(hitStartCircle(canvasMouseX, canvasMouseY)){
          fillPolyline();
          return;
      }
      storedLines.push({x:canvasMouseX,y:canvasMouseY});
      if(storedLines.length==1){
          startX=canvasMouseX;
          startY=canvasMouseY;
          ctx.fillStyle="green";
          ctx.beginPath();
          ctx.arc(canvasMouseX, canvasMouseY, radius, 0 , 2 * Math.PI, false);
          ctx.fill();
      }else{
          var c=storedLines.length-2;
          ctx.strokeStyle="orange";
          ctx.lineWidth=3;
          ctx.beginPath();
          ctx.moveTo(storedLines[c].x,storedLines[c].y);
          ctx.lineTo(canvasMouseX, canvasMouseY);
          ctx.stroke();
      }
    }

    function hitStartCircle(x,y){
        var dx=x-startX;
        var dy=y-startY;
        return(dx*dx+dy*dy<radius*radius)
    }
    function fillPolyline(){
        ctx.strokeStyle="red";
        ctx.fillStyle="blue";
        ctx.lineWidth=3;
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.beginPath();
        ctx.moveTo(storedLines[0].x,storedLines[0].y);
        for(var i=0;i<storedLines.length;i++){
            ctx.lineTo(storedLines[i].x,storedLines[i].y);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        storedLines=[];
    }

    $("#clear").click(function(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        storedLines=[];
    });

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

</head>

<body>
    <p>Click to draw lines</p>
    <p>Click back in the green circle to close+fill</p><br/>
    <canvas id="canvas" width=300 height=300></canvas><br/>
    <button id="clear">Clear Canvas</button>
</body>
</html>

[基于较少信息的上一个答案]

看起来您正在尝试:

  • 让用户点击画布上的点。
  • 在 storedLines[] 中收集这些点。
  • 稍后,使用 storedLines[] 绘制线条 + 填充颜色。
  • (我假设您不想在用户点击时立即绘制线条,因为您说“我需要检测绘制线条何时完成......”。)如果您确实想在用户点击时立即绘制,请给我一个发表评论,我也可以为您提供替代方案;)

如果我可以在您的代码中建议进行一些清理:

这是在画布上获取鼠标位置的好方法:

    // before you begin listening for mouseclicks, 
    // get the canvas’  screen position into offsetX/offsetY
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    // then when a mousedown event occurs
    // use e.clientX/Y (not e.pageX/Y) to get the mouse position on the canvas
    canvasMouseX=parseInt(e.clientX-offsetX);
    canvasMouseY=parseInt(e.clientY-offsetY);

当您实际使用上下文和存储线绘制路径时:

  • 要关闭路径,请将 context.closePath() 放在 context.stroke() 和 context.fill() 之前。
  • 设置一个填充样式和描边样式。
  • 执行 context.fill() 和 context.stroke() -- 如果不使用 fill(),则不会获得颜色填充。

    // close a path
    context.closePath();
    context.fillStyle=”blue”;
    context.strokeStyle=”rgb(180,80,95)”;
    context.fill();
    context.stroke();
    

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

<!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; padding:10px; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    ctx.strokeStyle="orange";
    ctx.font = '12px Arial';

    $("#canvas").mousedown(function(e){handleMouseDown(e);});

    function handleMouseDown(e){
      canvasMouseX=parseInt(e.clientX-offsetX);
      canvasMouseY=parseInt(e.clientY-offsetY);

      // Put your mousedown stuff here
      storedLines.push({x:canvasMouseX,y:canvasMouseY});
      var count=storedLines.length;
      var X=canvasMouseX-(count<10?4:7);
      ctx.strokeStyle="orange";
      ctx.fillStyle="black";
      ctx.lineWidth=1;
      ctx.beginPath();
      ctx.arc(canvasMouseX, canvasMouseY, 8, 0 , 2 * Math.PI, false);
      ctx.fillText(storedLines.length, X, canvasMouseY+4);
      ctx.stroke();
    }

    $("#draw").click(function(){
        ctx.strokeStyle="red";
        ctx.fillStyle="blue";
        ctx.lineWidth=3;
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.beginPath();
        ctx.moveTo(storedLines[0].x,storedLines[0].y);
        for(var i=0;i<storedLines.length;i++){
            ctx.lineTo(storedLines[i].x,storedLines[i].y);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        storedLines=[];
    });

    $("#clear").click(function(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        storedLines=[];
    });

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

</head>

<body>
    <p>Click to create storedLines[]</p>
    <p>Then press the Draw button to fill the path</p><br/>
    <canvas id="canvas" width=300 height=300></canvas><br/>
    <button id="clear">Clear Canvas</button>
    <button id="draw">Draw</button>
</body>
</html>
于 2013-03-20T15:37:26.450 回答
1

如果您的 storedLines 数组包含其中所有值的精确副本,那么您已经绘制了一个形状,否则您还没有...

例子:

你通过画三条线来画一个三角形

  1. Line1 - (0,0) 到 (10,0)

  2. Line2 - (10,0) 到 (5,10)

  3. Line3 - (5,10) 到 (0,0)

因此,所有点都有它的副本。

于 2013-03-20T07:37:43.923 回答