单击/拖动以使用Jquery在画布上同时绘制多条线

时间:2014-09-16 16:48:28

标签: javascript jquery html5-canvas

我感兴趣的是让用户点击并在画布元素上绘制一个直角三角形,但是当我第二次调用我的drawLine函数时,第一个被删除。这里的示例图:right_triangle_draw什么给出了?

  $("canvas").mousedown(function(event) {
      var totalOffsetX = 0;
      var totalOffsetY = 0;
      var canvasX = 0;
      var canvasY = 0;
      var currentElement = this;

      do {
          totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
          totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
      }
      while (currentElement = currentElement.offsetParent)

      startX = event.pageX - totalOffsetX;
      startY = event.pageY - totalOffsetY;

      $(this).bind('mousemove', function(e) {
          var xdiff = Math.abs(startX - e.pageX + totalOffsetX);
          var ydiff = Math.abs(startY - e.pageY + totalOffsetY);

          drawLine(startX, startY, e.pageX - totalOffsetX, e.pageY - totalOffsetY, direction);

          drawLine(startX, startY, e.pageX - totalOffsetX, startY, direction);

      });
  }).mouseup(function() {
      $(this).unbind('mousemove');
  });



  function drawLine(x, y, stopX, stopY, direction) {
          ctx.strokeStyle = 'rgba(0,155,205,0.8)';
          ctx.lineWidth = 3;
          ctx.clearRect(0, 0, can.width, can.height);
          ctx.beginPath();
          ctx.moveTo(x, y);
          ctx.lineTo(stopX, stopY);
          ctx.closePath();
          ctx.stroke();

1 个答案:

答案 0 :(得分:0)

每次画线时都要清除画布。尝试使用ctx.clearRect(0,0,can.width,can.height);在drawLine调用之前,在mouseMove函数上将其从drawLine中删除。