HTML5:如何让我的画布忘记旧像素?

时间:2012-03-14 04:16:24

标签: html5-canvas

我正在尝试制作一个可以通过鼠标操作的画布(拖动,绘图,点击......),这似乎是一项简单的任务。目前我已将它从鼠标按下的位置绘制到现在的位置,直到它被释放。但无论我是否清除画布,都会继续绘制该行的所有旧版本。我尝试过使用beginPath / closePath和fill而不是stroke;两种方法都导致线条永远不会出现。是否有一些我无法找到的绘制操作的“分隔符”?

可以查看和测试来源here,我也将其包含在下面。

<!DOCTYPE html>
<html>
  <head>
    <title>Canvas</title>
  </head>
  <body>
    <canvas id="test" width="640" height="480"></canvas>
    <script type="text/javascript">
      (function (){
        // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
        function getMousePos(obj, evt){
          // get canvas position
          var top = 0;
          var left = 0;
          while (obj && obj.tagName != 'BODY') {
            top += obj.offsetTop;
            left += obj.offsetLeft;
            obj = obj.offsetParent;
          }

          // return relative mouse position
          var mouseX = evt.clientX - left + window.pageXOffset;
          var mouseY = evt.clientY - top + window.pageYOffset;
          return {
            x: mouseX,
            y: mouseY
          };
        }
        var canvasElement = document.getElementById('test');

        if(canvasElement.getContext){
          var canvas = canvasElement.getContext('2d');
          var start = null;
          var end = null;
          var drawing = false;

          canvasElement.addEventListener('mousedown', function (event){
            var mousePos = getMousePos(canvasElement, event);
            start = mousePos;
            end = mousePos;

            drawing = true;
          }, false);
          canvasElement.addEventListener('mousemove', function (event){
            if(drawing){
              end = getMousePos(canvasElement, event);
            }
          }, false);
          function release(event){
            drawing = false;
          }
          canvasElement.addEventListener('mouseup', release, true);

          var FPS = 30;
          setInterval(function() {
            canvas.clearRect(0, 0, canvasElement.width, canvasElement.height);
            if(drawing && start != null){
              canvas.moveTo(start.x, start.y);
              canvas.lineTo(end.x, end.y);
              canvas.stroke();
            }
          }, 1000/FPS);
        }
      })();
    </script>
  </body>
</html>​

1 个答案:

答案 0 :(得分:2)

您需要使用beginPath和closePath创建路径,如下所示:

    canvas.clearRect(0, 0, canvasElement.width, canvasElement.height);
    if(drawing && start != null){
      canvas.beginPath();
      canvas.moveTo(start.x, start.y);
      canvas.lineTo(end.x, end.y);
      canvas.closePath();
      canvas.stroke();
    }

否则,您只需继续在现有路径中添加行。