JavaScript - 画布绘图 - 脚本不起作用

时间:2012-12-02 05:36:46

标签: javascript

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

<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>

1 个答案:

答案 0 :(得分: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;
  }