-1

如何在网页上添加功能,将单击的 xy 点显示为文本,然后可以复制和粘贴?

4

1 回答 1

0

我假设既然您编写了标记为“画布”的“保存功能”,那么您想要:

  • 让用户点击点,
  • 将这些点显示为可复制的文本。
  • 然后您将使用 json 将该文本保存在某处。

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

<!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; float:left;}
    #container{width:410px;}
    #log{ width:100px; height:300px; float:right;}
</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 storedPoints=[];

    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
      storedPoints.push({x:canvasMouseX,y:canvasMouseY});
      var count=storedPoints.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(storedPoints.length, X, canvasMouseY+4);
      ctx.stroke();
      $("#log").html(toHtml());
    }

    function toHtml(){
        htmlPoints="";
        for(var i=0;i<storedPoints.length;i++){
            htmlPoints+="<p>"+storedPoints[i].x+","+storedPoints[i].y+"</p>"
        }
        return(htmlPoints);
    }

    $("#clear").click(function(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        storedPoints=[];
        $("#log").html(toHtml());

    });

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

</head>

<body>
    <br/><p>Click on canvas to create points as text</p><br/>
    <button id="clear">Clear Canvas</button>
    <div id="container">
        <canvas id="canvas" width=300 height=300></canvas>
        <div id="log"></div>
    </div>
</body>
</html>
于 2013-03-20T16:36:54.630 回答