像Windows中的标准绘制程序一样,我试图创建一个非常基本的草图画布程序,用户可以在其中选择一个标尺工具在画布上进行绘制。我该如何实现?

我是一个初学者,所以如果答案尽可能简单,我将不胜感激。

谢谢!!

最佳答案

您可以使用包装在容器div中的2个重叠的画布。

然后在底部画布上绘制标尺标记。



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

<!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:20px; }
    #wrapper{
        position:relative;
        width:315px;
        height:215px;

    }
    #canvasBottom{
        position:absolute; top:0px; left:0px;
        border:1px solid red;
    }
    #canvasTop{
        position:absolute; top:15px; left:15px;
        border:1px solid red;
    }
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvasTop");
    var ctx=canvas.getContext("2d");
    var canvas2=document.getElementById("canvasBottom");
    var ctx2=canvas2.getContext("2d");

    ctx2.beginPath();
    for(var i=0;i<canvas.width;i+=10){
        var y=(i/100==parseInt(i/100))?0:10;
        ctx2.moveTo(i+15,y);
        ctx2.lineTo(i+15,15);
        var x=(i/100==parseInt(i/100))?0:10;
        ctx2.moveTo(x,i+15);
        ctx2.lineTo(15,i+15);
    }
    ctx2.stroke();


    var canvasOffset=$("#canvasTop").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#movelog").html("Move: "+ mouseX + " / " + mouseY);

      // Put your mousemove stuff here

    }

    $("#canvasTop").mousemove(function(e){handleMouseMove(e);});

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

</head>

<body>
    <p id="movelog">Move</p>
    <div id="wrapper">
        <canvas id="canvasBottom" width=315 height=215></canvas>
        <canvas id="canvasTop" width=300 height=200></canvas>
    </div>
</body>
</html>

10-05 23:23