0

我编写了一个使用 HTML5 画布的非常简单的 JavaScript。当用户在画布上单击鼠标时,脚本会获取他们的鼠标坐标,然后当他们按住鼠标移动鼠标时,它会绘制一条线,重复此过程直到他们松开鼠标。但它不起作用,我不知道为什么?在此先感谢您的帮助。

<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas>

<script>
// Canvas link
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

// Variables
var x1;
var y2;
var isPressed = false;

// Event listeners
context.addEventListener('mousedown', functionMouseDown, false);
context.addEventListener('mousemove', functionMouseMove, false);
context.addEventListener('mouseup', functionMouseUp, false);


function functionMouseDown() {
    // Get coordinates
    x1 = mousePos.x;
    y1 = mousePos.y;

    isPressed = true;
}

function functionMouseMove() {
     // If mouse is down and moved start drawing line
     if (isPressed == true) {
        drawLine();
     }
}

function functionMouseUp() {
    // Stop drawing line
    isPressed = false;
}

function drawLine() {
// Draw line
context.moveTo(x1,y1);
context.lineTo(x,y);
context.stroke();

// Set start coordinates to current coordinates
x1 = x;
y1 = y;
}
</script>
</body>
</html>
4

1 回答 1

3

这里有几个问题。你需要获取鼠标位置,而不是简单地存储在 mousePos.x/y 中。您通过鼠标移动事件,作为第一个参数传递给函数,该函数被添加为 mousemove、mousedown、mouseup 的侦听器。这是我修复它的方法

  function functionMouseDown(e) {
      // Get coordinates
      x1 = e.clientX
      y1 = e.clientY;

      isPressed = true;
  }

  function functionMouseMove(e) {
       // If mouse is down and moved start drawing line
       if (isPressed == true) {
          drawLine(e);
       }
  }

  function functionMouseUp() {
      // Stop drawing line
      isPressed = false;
  }

  function drawLine(e) {
  // Draw line
  var x = e.clientX;
  var y = e.clientY;
  context.moveTo(x1,y1);
  context.lineTo(x,y);
  context.stroke();

  // Set start coordinates to current coordinates
  x1 = x;
  y1 = y;
  }
于 2012-12-02T06:01:41.147 回答