if you want a creative solution, heres one that youl find very creative:
1: use [element].requestPointerLock()
2: create a new image of a mouse cursor. (here's one you might like)
3: create 2 new variables x and y, and lock the image position to them.
4: write:
document.addEventListener('mousemove', function(){
x += window.movementX;
y += window.movementY;
});
5: enter some if statements to keep the mouse image inside the element. make sure to keep the if statements' 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);
}
});
make sure to replace "element" with the name of the variable storing your element if you intend on using this exact code.
and dont 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. it has all these steps implemented and tested. just click the screen to start, and press [Esc] to turn it off.
<style>
cursor: none;
</style>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>New webpage</title>
</head>
<body>
<img id="div" src="https://lh3.googleusercontent.com/proxy/-3xjuhfpWxL0kfTWr6B2ZGmIKt7xWJ4d-3XcKg4m3wO4sMEen9cg_euf2xlkxwIrSbzQ0lOkDcUUI8TjEV172KVSPshQta9-Stql5WtHpzwkFrHQOY8X2S_PCEHg6GYJW6Zjr6PJeeFBNnLwdiAtB4XpWQ" 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>