кузьмич кузьмич - 7 days ago 6
HTML Question

why rеmоvеEvеntListеnеr is not wоrk?

i want to get mouse position only when my mouse button is press.
Now it can getting coordinates when i press my mouse, but it can not stop when i unpressed



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


It looks like your post is mostly code; please add some more details.

Answer

You have to pass same argument function in both addEventListener and removeEventListener to make it work. try this one:

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>

Comments