我在指针锁定方面遇到了麻烦。我的代码看起来像这样......
Canvas = document.createElement('canvas');
...(Parameters)...
document.body.appendChild(Canvas);
Canvas.requestPointerLock = Canvas.requestPointerLock ||
element.mozRequestPointerLock ||
element.webkitRequestPointerLock;
Canvas.requestPointerLock();
当我运行我的代码时,指针锁没有任何反应(其他一切都运行得很快)。我展示的代码就是我认为与该问题相关的代码,但如果需要更多来自我的程序的代码,请告诉我。
答案 0 :(得分:3)
如果我们在click事件中移动'requestPointerLock()',它可以正常工作。分享以下示例代码以供参考。
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Pointer lock</title>
<style type="text/css">
html {font-size: 10px; font-family: sans-serif;}
canvas {display: block; margin: 0 auto; border: 1px solid black;}
</style>
</head>
<body>
<canvas width="640" height="360">
Your browser does not support HTML5 canvas
</canvas>
</body>
<script type="text/javascript">
// setup of the canvas
window.addEventListener('load', eventWindowLoaded, false);
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
function eventWindowLoaded() {
canvasDraw();
}
var x = 50;
var y = 50;
function canvasDraw() {
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.clientWidth,canvas.clientHeight);
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(x,y,20,0,degToRad(360), true);
ctx.fill();
}
// pointer lock object forking for cross browser
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock;
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock;
canvas.onclick = function() {
canvas.requestPointerLock();
}
// pointer lock event listeners
// Hook pointer lock state change events for different browsers
document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
function lockChangeAlert() {
if(document.pointerLockElement === canvas ||
document.mozPointerLockElement === canvas) {
console.log('The pointer lock status is now locked');
document.addEventListener("mousemove", canvasLoop, false);
} else {
console.log('The pointer lock status is now unlocked');
document.removeEventListener("mousemove", canvasLoop, false);
}
}
function canvasLoop(e) {
var movementX = e.movementX || e.mozMovementX || 0;
var movementY = e.movementY || e.mozMovementY || 0;
x += movementX;
y += movementY;
canvasDraw();
console.log("X position: " + x + ', Y position: ' + y);
}
// helper function
function degToRad(degrees) {
var result = Math.PI/180 * degrees;
return result;
}
</script>
</html>
答案 1 :(得分:2)
According to the WC3 Docs on pointerlock
:
requestPointerLock
如果用户已通过默认解锁用户手势退出指针锁定,或者之前未为此文档输入指针锁定,则必须在{{1}之前由文档接收由于参与手势而生成的事件将会成功。
It then talks about engagement gestures below.
订婚手势
用户代理因用户交互而生成的事件,旨在与页面进行交互。例如
requestPointerLock
,但不是click
。参与手势是允许通过添加mousemove
和keypress
来显示弹出窗口的定义中包含的任何事件。
因此,为了让您的代码正常工作,应该从参与动作调用keyup
,例如requestPointerLock
事件处理程序。