3 回答
TA贡献2036条经验 获得超8个赞
您可以使用“setInterval”并可以在每个控制台之间指定您自己的等待时间(以毫秒为单位)
var canvas = document.getElementById('canvas');
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
var mousePosition, holding;
function myInterval() {
var setIntervalId = setInterval(function() {
if (!holding) clearInterval(setIntervalId);
getCursorPosition(canvas, mousePosition);
}, 100); //set your wait time between consoles in milliseconds here
}
canvas.addEventListener('mousedown', function() {
holding = true;
myInterval();
})
canvas.addEventListener('mouseup', function() {
holding = false;
myInterval();
})
canvas.addEventListener('mouseleave', function() {
holding = false;
myInterval();
})
canvas.addEventListener('mousemove', function(e) {
mousePosition = e;
})
TA贡献1815条经验 获得超13个赞
你应该在这里使用 mousemove 事件:
var holding = false;
var canvas = document.getElementById('canvas');
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
canvas.addEventListener('mousedown', function(e) {
holding = true;
})
canvas.addEventListener('mouseup', function(e) {
holding = false;
})
canvas.addEventListener('mousemove', function(e) {
if(holding == true){
getCursorPosition(canvas, e)
}
})
编辑:您还需要在离开按钮时将保持设置为 false
canvas.addEventListener('mouseleave', function(e) {
holding = false;
})
TA贡献1775条经验 获得超8个赞
尝试这个...
var canvas = document.getElementById('canvas');
var mouseIsDown = false;
var mouseInterval = null;
var mouseEvent = null;
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
canvas.addEventListener('mousedown', function (e) {
mouseEvent = e;
mouseIsDown = !mouseIsDown;
getCursorPosition(canvas, e)
mouseInterval = setInterval(() => {
getCursorPosition(canvas, mouseEvent)
}, 100);
})
canvas.addEventListener('mousemove', function (e) {
mouseEvent = e;
})
canvas.addEventListener('mouseup', function (e) {
mouseIsDown = !mouseIsDown;
clearInterval(mouseInterval);
})
添加回答
举报