if you need a creative solution, here is what you find very creative:
1: use [element]. requestPointerLock ()
2: create a new mouse cursor image. (you may like it here)
3: create 2 new variables x and y and fix the position of the image to them.
4: write:
document.addEventListener('mousemove', function(){ x += window.movementX; y += window.movementY; });
5: enter some if statements to hold the mouse image inside the element. make sure the if statements are inside the EventListener above:
document.addEventListener('mousemove', function(){ x += window.movementX; y += window.movementY; if(x < parseFloat(element.style.left)){ x = parseFloat(element.style.width); } if(x > parseFloat(element.style.left) + parseFloat(element.style.width)){ x = parseFloat(element.style.width) + parseFloat(element.style.width); } if(y < parseFloat(element.style.top)){ y = parseFloat(element.style.top); } if(y > parseFloat(element.style.top) + parseFloat(element.style.height)){ y = parseFloat(element.style.top) + parseFloat(element.style.height); } });
Be sure to replace the "element" with the name of the variable storing your element if you intend to use this exact code.
and don't forget to update the position of your element by assigning x and y to its position every time you use it. try the code below. All these steps are implemented and verified. just tap the screen to start, and press [Esc] to turn it off.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>New webpage</title> </head> <body> <img id="div" src="https://b.sccpre.cat/mypng/small/51- 518482_mouse-svg-cursors-mac-transparent-background-mouse-cursor.png" alt="hi" style="position: absolute; width: 20px; height: 20px;"> <div id="cage" style="width: 200px; height: 200px; background- color: lightgray; left: 0px; top: 0px;"> </div> <h1 id="tx">click to start</h1> </body> <script> var d = document.getElementById('div'); var tx = document.getElementById('tx'); document.addEventListener('click', function(){ var txt = tx.textContent; if(txt === "click to start"){ d.requestPointerLock(); tx.textContent = "click to stop"; } if(txt === "click to stop"){ document.exitPointerLock(); tx.textContent = "click to start"; } }); var x = 0; var y = 0; var cage = document.getElementById('cage'); document.addEventListener("mousemove", function(e){ x += e.movementX; y += e.movementY; if(x < parseFloat(cage.style.left)){ x = parseFloat(cage.style.left); } if(x > parseFloat(cage.style.left) + parseFloat(cage.style.width)){ x = parseFloat(cage.style.left) + parseFloat(cage.style.width); } if(y < parseFloat(cage.style.top)){ y = parseFloat(cage.style.top); } if(y > parseFloat(cage.style.top) + parseFloat(cage.style.height)){ y = parseFloat(cage.style.top) + parseFloat(cage.style.height); } d.style.left = x + 'px'; d.style.top = y + 'px'; }); </script> </html>
source share