1

以下代码在单击按钮时清除画布

context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears

但是,当我尝试重新绘制它时,会出现我不希望它出现的旧图。我想开始在新的空白画布上作画

http://jsfiddle.net/umwc5/

我该如何做到这一点?

如果您想查看整个代码..

  $(function () {
  var c = document.getElementById("canvas");
  var context = c.getContext("2d");
  var clickX = new Array();
  var clickY = new Array();
  var clickDrag = new Array();
  var paint;

  $('#canvas').mousedown(function (e) {
      var mouseX = e.pageX - this.offsetLeft;
      var mouseY = e.pageY - this.offsetTop;

      paint = true;
      addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
      redraw();
  });


  $('#canvas').mousemove(function (e) {
      if (paint) {
          addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
          redraw();
      }
  });

  $('#canvas').mouseup(function (e) {
      paint = false;
  });

  $('#canvas').mouseleave(function (e) {
      paint = false;
  });

  $('#clear').click(function (e) {
      e.stopPropagation();
      context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears

  });

  function addClick(x, y, dragging) {
      clickX.push(x);
      clickY.push(y);
      clickDrag.push(dragging);
  }

  function redraw() {
      context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas

      context.strokeStyle = "#000000";
      context.lineJoin = "round";
      context.lineWidth = 2;

      for (var i = 0; i < clickX.length; i++) {
          context.beginPath();
          if (clickDrag[i] && i) {
              context.moveTo(clickX[i - 1], clickY[i - 1]);
          } else {
              context.moveTo(clickX[i] - 1, clickY[i]);
          }
          context.lineTo(clickX[i], clickY[i]);
          context.closePath();
          context.stroke();
      }
  }

  });
4

1 回答 1

0

您必须清除以下数组clickXclickY并且clickDrag

context.clearRect(0, 0, context.canvas.width, context.canvas.height);
clickX = []; // clear mouse "logs"
clickY = [];
clickDrag = [];

工作的jsFiddle

当您单击或拖动鼠标时,将addClick调用该方法,该方法将填充数组clickXclickYclickDrag使用鼠标坐标。当redraw调用该方法时,它会再次在画布上绘制点。因此,清除这些数组将解决您的问题。

于 2013-08-22T09:06:39.217 回答