使用Canvas,HTML5绘制鼠标移动?

时间:2014-04-17 18:23:37

标签: javascript html5 canvas

我想要实现的是在单击鼠标时在画布上绘制线条的简单功能。

我已经在线查看了代码,并且我正在尝试自己实现它,但它不会起作用。

到目前为止:

<html>
<canvas id="myCanvas" width="400" height="500"> </canvas>
</html>

<script type="text/javascript">
var el = document.getElementById('myCanvas');
    var ctx = el.getContext('2d');
    var isDrawing;

    el.onmousedown = function(e) {

      isDrawing = true;
      ctx.moveTo(e.clientX, e.clientY);
    };

    el.onmousemove = function(e) {
      if (isDrawing) {
        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
      }
    };
    el.onmouseup = function() {

      isDrawing = false;
    };

</script>

然而,这并没有在画布上输出任何内容。我不完全理解代码的事件处理方面(即e.clientX,e.clientY) 我怀疑我必须在这些代码中添加这些代码以获得所需的效果吗?

2 个答案:

答案 0 :(得分:0)

匆匆一瞥,你错过了一个&#34;&gt;&#34;在第2行的末尾。

答案 1 :(得分:0)

有几个问题:

  • 根据画布的偏移量调整鼠标位置(除非画布位于浏览器的左上角)

  • 在mousemove中执行所有绘图命令(否则您将使用每个ctx.stroke重新执行该行)

以下是示例代码和演示:http://jsfiddle.net/m1erickson/kkLrT/

<!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; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var BB=canvas.getBoundingClientRect();
    var offsetX=BB.left;
    var offsetY=BB.top;

    var lastX,lastY;
    var isDown=false;

    canvas.onmousedown=handleMousedown;
    canvas.onmousemove=handleMousemove;
    canvas.onmouseup=handleMouseup;


    function handleMousedown(e){
         e.preventDefault();
         e.stopPropagation();
         lastX=e.clientX-offsetX;
         lastY=e.clientY-offsetY;
         isDown=true;
    }

    function handleMouseup(e){
         e.preventDefault();
         e.stopPropagation();
         isDown=false;
    }

    function handleMousemove(e){
         e.preventDefault();
         e.stopPropagation();

         if(!isDown){return;}

         var mouseX=e.clientX-offsetX;
         var mouseY=e.clientY-offsetY;

         ctx.beginPath();
         ctx.moveTo(lastX,lastY);
         ctx.lineTo(mouseX,mouseY);
         ctx.stroke();

         lastX=mouseX;
         lastY=mouseY;
    }


}); // end $(function(){});
</script>
</head>
<body>
    <h4>Drag mouse to draw.</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>