簡體   English   中英

JavaScript-畫布繪圖-腳本不起作用

[英]JavaScript - Canvas Drawing - Script Doesn't Work

我編寫了使用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>

這里有幾個問題。 您需要獲取鼠標位置,而不僅僅是將其存儲在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;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM