实现目标
当鼠标移动到视口边界时,鼠标从对向一侧出现
实现效果
实现原理
虽然js中并没有直接提供可以修改鼠标位置的方法,但是浏览器提供了一个requestPointerLock 方法。通过该方法可以访问原始的鼠标运动,把鼠标事件的目标锁定到一个特定的元素,同时隐藏视图中的指针光标(可通过 ESC 显示),并且可以消除鼠标在一个方向上移动的边界限制,但是此方法不允许直接使用,需要用户触发事件后才能生效,例如在click、mousedown等事件中触发才能生效。应用该方法之后mousemove事件中的pageX及pageY将不会随着鼠标的移动而改变,这时候需要使用事件中的 movementX 和 movementY 来获取鼠标的相对位移。如果要解除鼠标锁定状态则需要调用 exitPointerLock 这个方法。
各浏览器兼容性
完整代码
代码中有用到一个图片资源,有需要的可以复制下载。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100vh;
overflow: hidden;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 120px;
text-align: center;
background-color: skyblue;
border-radius: 10px;
padding: 20px 0;
cursor: pointer;
font-weight: 600;
font-size: 22px;
}
</style>
</head>
<body>
<div class="box">
<div class="posiX">x: 0</div>
<div class="posiY">y: 0</div>
</div>
<script>
let box = document.querySelector('.box')
let posiX = document.querySelector('.posiX')
let posiY = document.querySelector('.posiY')
let img;
let screenWidth = document.documentElement.clientWidth
let screenHeight = document.documentElement.clientHeight
let imgWidth = 24
let imgHeight = 24
let countX = 0
let countY = 0
box.addEventListener('mousedown', (e) => {
img = document.createElement('img')
img.src = './images/cursor.png'
img.style.position = 'absolute'
img.style.top = e.pageY - imgHeight / 2 + 'px'
img.style.left = e.pageX - imgWidth / 2 + 'px'
img.style.width = imgWidth + 'px'
img.style.height = imgHeight + 'px'
document.body.appendChild(img)
document.body.requestPointerLock()
document.addEventListener('mousemove', mousemove)
document.addEventListener('mouseup', mouseup)
})
function mousemove(e) {
img.style.top = img.offsetTop + e.movementY + 'px'
img.style.left = img.offsetLeft + e.movementX + 'px'
countX += e.movementX
posiX.innerText = `x: ${countX}`
countY += e.movementY
posiY.innerText = `y: ${countY}`
if (img.offsetLeft > screenWidth + imgWidth) {
img.style.left = -imgWidth + 'px'
}
if (img.offsetLeft < -imgWidth) {
img.style.left = screenWidth + imgWidth + 'px'
}
if (img.offsetTop < -imgHeight) {
img.style.top = screenHeight + imgHeight + 'px'
}
if (img.offsetTop > screenHeight + imgHeight) {
img.style.top = -imgHeight + 'px'
}
}
function mouseup(e) {
img.remove()
document.exitPointerLock()
document.removeEventListener('mousemove', mousemove)
document.removeEventListener('mouseup', mouseup)
}
</script>
</body>
</html>