LANGUAGE/HTML & CSS & JS 2018. 12. 18. 05:49

!markdown


# Javascript (자바스크립트)


마우스가 안보이게 하는 방법은 2가지가 있다.


### 1. CSS를 이용한 마우스 커서 숨기기


- css


```html

<style>

body { cursor:none; }

</style>

```


- javascript


```html

<script>

document.body.style.cursor = 'none';

</script>

```




### 2. element.requestPointerLock()을 이용한 마우스 숨기기


위의 CSS로 cursor속성을 none하는 것으로는 마우스가 해당 객체의 범위에서 넘어서면 마우스가 삐져나온다.


마치 객체에 마우스가 빠져들어가 취소하기 전까지는 화면에 튀어나오지 않길 바란다면?? 


`element.requestPointerLock();` 을 사용하자.


아마도 FPS게임을 구현한다거나, 특별한 무언가를 원하는 분들이라면 고려해볼 것 같다.


```

document.body.requestPointerLock();

```


`원하는 객체로부터 호출`할 수 있다. 여기서는 `document`를 예로 들었다.


```html

<script>

document.addEventListener('click', function(event){

document.requestPointerLock();

});


document.addEventListener('mousemove', function(event){

console.log( event.movementX );

console.log( event.movementY );

});

</script>

```


- 특징


  1. 자동설정 호출은 불가능하며 'click'과 같은 `이벤트호출을 통해서만` 사용할 수 있다. (사용자에게 혼선과 악의적으로 피해를 줄 수 있기 때문인 것 같다. - `element.requestFullscreen()`과 같은 성격인듯..)


  2. PointerLock상태에서는 마우스의 움직임을 `event.movementX`, `event.movementY`로 이동된 만큼의 값을 얻을 수 있다. (위치값이 아니다.)


  3. Chrome과 Firefox는 된다는데.. 다른 Browser에서 구현되었는지 모르겠다...


- 종료


```javascript

document.exitPointerLock();

```

- 이벤트


```javascript

document.body.addEventListener("pointerlockchange", function(event){

    if (document.pointerLockElement === document.body) {

        //TODO: Implements..

    }

});

```

- Vendor Prefix


```javascript

element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;

element.requestPointerLock();

```


```javascript

document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;

document.exitPointerLock();

```






### 참고


- Hide Mouse Cursor when it's within HTML5 Canvas Javascript: [https://stackoverflow.com/questions/6892502/hide-mouse-cursor-when-its-within-html5-canvas-javascript/6892518](https://stackoverflow.com/questions/6892502/hide-mouse-cursor-when-its-within-html5-canvas-javascript/6892518)


- Is it possible to hide the cursor in a webpage using CSS or Javascript?: [https://stackoverflow.com/questions/1071356/is-it-possible-to-hide-the-cursor-in-a-webpage-using-css-or-javascript/1071363#1071363](https://stackoverflow.com/questions/1071356/is-it-possible-to-hide-the-cursor-in-a-webpage-using-css-or-javascript/1071363#1071363)


- Element.requestPointerLock(): [https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock)


- Pointer Lock and First Person Shooter Controls: [https://www.html5rocks.com/en/tutorials/pointerlock/intro/](https://www.html5rocks.com/en/tutorials/pointerlock/intro/)