我只想在按下鼠标按钮时获得鼠标位置。
现在,当我按下鼠标时它可以获取坐标,但是当我按下时它无法停止



<!DOCTYPE HTML>
<html>

<head>

  <body style="background-color:3F6E6F;">
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
</head>

<body>

  <canvas id="myCanvas" width="1200" height="1000" onmousedown="mouseDown()" onmouseup="mouseUp()"></canvas>
  <script>
    function writeMessage(canvas, message) {
      var context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.font = '18pt Calibri';
      context.fillStyle = 'black';
      context.fillText(message, 10, 25);
    }

    function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
      };
    }


    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');


    function mouseUp() {
      canvas.removeEventListener('mousemove', mouseDown)
        // alert('44')
    }

    function mouseDown() {
      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      }, false);
    }
  </script>
</body>

</html>

最佳答案

您必须在functionaddEventListener中都传递相同的参数removeEventListener才能起作用。试试这个:



function writeMessage(canvas, message) {
  var context = canvas.getContext('2d');
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.font = '18pt Calibri';
  context.fillStyle = 'black';
  context.fillText(message, 10, 25);
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

//create function here
function move(evt) {
  var mousePos = getMousePos(canvas, evt);
  var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
  writeMessage(canvas, message);
}

function mouseUp() {
  //pass the same arguments
  canvas.removeEventListener('mousemove', move, false)
    // alert('44')
}


function mouseDown() {
  //pass the same arguments
  canvas.addEventListener('mousemove', move, false);
}

body {
  background-color: 3F6E6F;
  margin: 0px;
  padding: 0px;
}
canvas {
  background-color: green;
}

<canvas id="myCanvas" width="1200" height="1000" onmousedown="mouseDown(event)" onmouseup="mouseUp(event)"></canvas>

09-28 11:00