用JS制作绘图应用程序?

时间:2019-06-12 09:41:46

标签: javascript html events canvas

我想用JS制作绘图应用程序。因此,我开始用HTML创建画布,并编写一些JS代码。但是,当我运行脚本时,只能画点,而我想用鼠标手动画线。

能帮我吗?

window.addEventListener("load", function(){
  var clear = document.getElementById("clear");
  var paint = false;

  can = document.querySelector("canvas");
  context = can.getContext("2d");
  can.addEventListener("mouseup", finish);
  can.addEventListener("mousemove", draw);
  clear.addEventListener("click", clearContent);
  can.addEventListener("mousedown", painting);

  function clearContent(){	
    context.clearRect(0, 0, can.width, can.height);
  }

  function painting(){
    paint = true;
  }

  function finish(){
    paint = false;
  }

  function draw(e){
    if (!paint) return 0;
      context.strokeStyle="black";
      context.lineWidth = 5;
      context.lineCap = "round";
      context.beginPath();
      context.moveTo(e.clientX, e.clientY);
      context.lineTo(e.clientX, e.clientY);
      context.stroke();
  }
});
canvas { border: 1px solid }
<canvas></canvas>
<br>
<button id="clear">Clear</button>

1 个答案:

答案 0 :(得分:0)

您需要从上一个点而不是当前点绘制直线。这样做非常简单,因为画布上下文会记住上一点。另外,请勿调用beginPath,因为这会中断要连接的点的顺序。

您还可以使用更好的方法来精确定位确切的坐标。

查看此代码变体:

window.addEventListener("load", function(){
  var clear = document.getElementById("clear");
  var paint = false;

  can = document.querySelector("canvas");
  context = can.getContext("2d");
  can.addEventListener("mouseup", finish);
  can.addEventListener("mousemove", draw);
  clear.addEventListener("click", clearContent);
  can.addEventListener("mousedown", painting);

  function clearContent(){	
    context.clearRect(0, 0, can.width, can.height);
  }

  function painting(){
    paint = true;
    context.beginPath(); /// <--- move this here
  }

  function finish(){
    paint = false;
  }

  function draw(e){
    if (!paint) return 0;
      var rect = e.target.getBoundingClientRect();
      var x = e.clientX - rect.left;
      var y = e.clientY - rect.top;
      context.strokeStyle="black";
      context.lineWidth = 5;
      context.lineCap = "round";
      // Don't do any of these here:
      // context.beginPath();
      // context.moveTo(x, y);
      // ... only draw line from previous point:
      context.lineTo(x, y);
      context.stroke();

  }
});
canvas { border: 1px solid }
<canvas></canvas>
<br>
<button id="clear">Clear</button>