在画布上绘制形状

时间:2013-03-20 07:22:24

标签: javascript jquery html5 html5-canvas

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

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

2 个答案:

答案 0 :(得分: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);

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

  • 要关闭路径,请将context.closePath()放在context.stroke()和context.fill()之前。
  • 设置fillStyle和strokeStyle。
  • 执行context.fill()和context.stroke() - 如果不填充(),则不会获得颜色填充。

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

答案 1 :(得分:1)

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

示例:

  
    

通过绘制三行来绘制三角形

  
     
      
  1. 第1行 - (0,0)到(10,0)

  2.   
  3. 第2行 - (10,0)至(5,10)

  4.   
  5. 第3行 - (5,10)至(0,0)
  6.         
        

    所以,所有的点都有它的副本。