javascript - 如何为 Canvas 创建标尺工具?

标签 javascript html canvas

与 Windows 中的标准绘图程序一样,我正在尝试创建一个非常基本的草图 Canvas 程序,用户可以在其中选择一个标尺工具在 Canvas 上绘图。我如何实现这一目标?

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

谢谢!!

最佳答案

您可以使用 2 个重叠的 Canvas 包裹在一个容器 div 中。

然后在底部 Canvas 上绘制您的标尺标记。

enter image description here

这是代码和 fiddle :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>

关于javascript - 如何为 Canvas 创建标尺工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434728/

相关文章:

Android canvas,如何从现有路径中获取子路径?

javascript - 通过无限滚动回到相同的位置

javascript - 扩展中的 Microsoft Edge 通知

javascript - 根据用户指定的数字动态添加 HTML 表单字段

javascript - 如何在 HTML Canvas 上渲染图标字体,尤其是 Material Design 图标字体?

javascript - 为什么 Canvas 上什么也没有出现?

javascript - react : input type ="checkbox" onChange not triggered

javascript - Angular 应用程序因一行代码而损坏,仅适用于 Safari,可在所有其他浏览器中工作

html - CSS `height: calc(100vh);` 与 `height: 100vh;`

html - 对 css 和 html 没有响应