0

我有这段代码,它在点击和拖动时在画布周围拖动一个球。

canvas.addEventListener('mousedown', function () {
  var initialClickX = mouse.x;
  var initialClickY = mouse.y;
  var initialBallX = ball.x;
  var initialBallY = ball.y;

  canvas.addEventListener('mousemove', function() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }, false);

}, false);

function onMouseMove(initialClickX, initialClickY, mouseX, mouseY, initialBallX,     initialBallY){
    ball.x = mouseX + initialBallX - initialClickX;
    ball.y = mouseY + initialBallY - initialClickY;
    draw();
}

问题是,当我鼠标向上时,我无法让球停止拖动。我知道我需要添加:

    canvas.removeEventListener('mousemove', function() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }, false);

但是因为该函数在包装器中,所以上面没有任何效果,球仍然粘在我的光标上。任何人都可以提出解决这个问题的方法吗?

4

1 回答 1

2

不要使用匿名函数。您需要保留对事件侦听器函数的引用以供以后删除。

canvas.addEventListener('mousedown', function () {
  var initialClickX = mouse.x;
  var initialClickY = mouse.y;
  var initialBallX = ball.x;
  var initialBallY = ball.y;

  function wrapper() {
      onMouseMove(initialClickX, initialClickY, mouse.x, mouse.y, initialBallX, initialBallY)
  }

  canvas.addEventListener('mousemove', wrapper, false);

  // some time later
  canvas.removeEventListener('mousemove', wrapper);

}, false);
于 2013-06-21T15:37:02.950 回答