隐藏光标并使用Javascript停止移动

时间:2012-05-29 18:28:20

标签: javascript html browser cursor

我正在制作一款3D游戏,其中相机需要与“魔兽世界”完全相同。这意味着,一旦点击屏幕,光标就会消失,当移动鼠标时,相机会围绕焦点(播放器)旋转。

我制作了大部分代码,单击屏幕时光标确实消失了,但问题是它仍在移动,即使它没有显示。这感觉不自然,我想让光标一直呆在同一个地方。

那么,我如何使用Javascript实现这一目标?

唯一的支持请求是最新版本的Chrome和Firefox。

2 个答案:

答案 0 :(得分:3)

由于其带来的安全隐患,您无法像在JavaScript中那样操纵光标的位置。

答案 1 :(得分:3)

如果我的问题是正确的

不能通过javascript,你需要闪光灯。

但是,有些人正在进行,

Pointer lock api

更新:(我有空闲时间,所以我玩了它)

你可以试试这样的东西,它不完美,不推荐,当原始鼠标到达屏幕边框时它会失败(但是你可以限制包装中的鼠标移动,这将解决问题)。

<强> HTML

<body style='width:100%;min-height:800px;overflow:hidden'>  
<img id='fakeCursor' src='http://i50.tinypic.com/359d3km.jpg'  style='z-index:1000;position:absolute;display:none' />  
<div href='javascript:void(0);' style='position:absolute;left:50px;top:10px;width:100px;height:100px;background:gray;' onclick='console.log("fake click 1");return false;'>Fake click 1</div>
<div href='javascript:void(0);' style='position:absolute;left:50px;top:130px;width:100px;height:100px;background:gray;' onclick='console.log("fake click 2");return false;'>Fake click 2</div>
</body>

<强>使用Javascript:

var clientX,clientY;   
var fakeCursor = document.getElementById('fakeCursor'); 

var isFakeMouse = false;
document.onclick = function(e){
    if(isFakeMouse){    
        if(document.elementFromPoint(fakeCursor.style.left,fakeCursor.style.top)!=null){
            document.elementFromPoint(fakeCursor.style.left,fakeCursor.style.top).click();
            return false;
        }
        fakeCursor.style.display = 'inline';
        fakeLeft = clientX;
        fakeTop = clientY;
        var mouseLastLeft = -1;
        var mouseLastTop = -1;
        document.onmousemove = function(e){  
            if(mouseLastLeft ===-1 && mouseLastTop ===-1){
                mouseLastLeft = e.clientX;
                mouseLastTop = e.clientY;
                return;
            } 
            fakeCursor.style.left = (parseInt(fakeCursor.style.left) + ((mouseLastLeft - e.clientX)*-1)) + 'px';
            fakeCursor.style.top = (parseInt(fakeCursor.style.top) + ((mouseLastTop - e.clientY)*-1)) + 'px'; 
            mouseLastLeft = e.clientX;
            mouseLastTop = e.clientY;
        }
    }
    else{
        isFakeMouse = true;
        document.body.style.cursor = "none";
        fakeCursor.style.display = 'none';
        fakeCursor.style.left = clientX = e.clientX;
        fakeCursor.style.top = clientY = e.clientY;
        document.onmousemove = null;
    }
} 

在这里,首先点击documentreal mouse隐藏。当用户再次点击document时,real mouse仍然会被隐藏,而新的fake mouse(图片)将取而代之。 fake mouse的位置与用户离开real mouse的位置相同。 fake mouse工作(尝试)像real mouse一样工作。

对不起内联css和javascrict