gpt4 book ai didi

javascript - 为什么removeEventListener不起作用?

转载 作者:行者123 更新时间:2023-12-02 13:53:40 26 4
gpt4 key购买 nike

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

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

最佳答案

您必须在 addEventListenerremoveEventListener 中传递相同的参数 function 才能使其工作。试试这个:

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>

关于javascript - 为什么removeEventListener不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com