I have a canvas
element and a div.coordinates
element that follows the mouse around when the mouse moves on the canvas. What I am trying to do is make the .coordinates
disappear if the mouse hasn't been moving on the canvas in the last 1 second.
<canvas></canvas>
canvas {
max-width: auto;
outline: 1px solid #283028;
align-self: center;
}
.coordinates {
top: 50px;
position: absolute;
height: 40px;
width: 60px;
background-color: rgba(20, 20, 20, 0.3);
border-radius: 10px;
display: none;
}
let coordinates = document.createElement("div");
coordinates.className = "coordinates";
let time = undefined;
const trackCanvasMouse = (e) => {
if (!time) {
time = Date.now();
}
setTimeout(() => {
if (time == Date.now()) {
coordinates.style.display = "none";
time = undefined;
}
}, 1000);
coordinates.style.top = `${e.clientY}px`;
coordinates.style.left = `${e.clientX}px`;
coordinates.style.display = "inline";
};
const canvas = document.querySelector("canvas");
canvas.addEventListener("mousemove", trackCanvasMouse);
canvas.width = 520;
canvas.height = 520;
document.querySelector("body").appendChild(coordinates);
I tried using Time.now()
and setTimeout
to see if an event has been triggered, but couldn't make it work.
Thanks for your time
This will show a span coords while the mouse is moving and disapear after the mouse stops for a second. What you want to do is keep track of the previous timeout and cancel it each time the mousemove event fires.
let timeout; const coords = document.getElementById('coords'); document.addEventListener("mousemove", function() { coords.style.display = "block"; if (timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { coords.style.display = "none"; }, 1000) });
#coords { display: none; }
<span id="coords">Coords</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.