从一个新的HTML5画布开始

时间:2013-08-22 09:01:05

标签: javascript jquery html5-canvas

以下代码在按钮上单击

清除画布
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();
      }
  }

  });

1 个答案:

答案 0 :(得分:0)

您必须清除以下数组clickXclickYclickDrag

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

<强> Working jsFiddle

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