html, javascript 키보드 이벤트

ginseng 2021. 2. 27. 12:05

javascript로 키보드 이벤트를 제어할 수 있습니다.

 

우선 이벤트를 추가합니다.

 

1
2
document.addEventListener("keydown",keyPush);
document.addEventListener("keyup",keyPull);
cs

 

여기서 addEventListener의 첫번째 매개변수는 자신이 추가하고자하는 이벤트를 입력합니다.

 

키보드 이벤트에는 keydown, keyup 등이 있습니다.

 

keydown의 경우 누르는 순간의 이벤트이고,

 

keyup의 경우 눌렀다 놓는 순간의 이벤트입니다.

 

두번째 매개변수는 이벤트가 발생할때 실행되는 함수입니다.

 

이를 이용하여 키보드버튼의 움직임을 구현할 수 있습니다.

 

우선 4가지 방향을 설정하고 해당하는 keyCode가 눌렸을때 해당하는 연산을 시행하면 됩니다.

 

또 동시에 눌렀을때의 연산과 서로 반대되는 키를 반복해서 누를때 발생하는 오류를 해결합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
        function keyPush(evt) {
            switch (evt.keyCode) {
                case 37:
                    if(rv==1)pr = 1;
                    lv = -1; rv=0;
                    break;
                case 38:
                    if(bv==1)pb = 1;
                    tv = -1; bv=0;
                    break;
                case 39:
                    if(lv==-1)pl = 1;
                    rv = 1; lv=0;
                    break;
                case 40:
                    if(tv==-1)pt = 1;
                    bv = 1; tv=0;
                    break;
            }
        }
        function keyPull(evt) {
            switch (evt.keyCode) {
                case 37:
                    if(pr == 1)rv=1;
                    lv = 0;
                    pl=0;
                    break;
                case 38:
                    if(pb == 1)bv=1;
                    tv = 0;
                    pt=0;
                    break;
                case 39:
                    if(pl == 1)lv=-1;
                    rv = 0;
                    pr=0;
                    break;
                case 40:
                    if(pt == 1)tv=-1;
                    bv = 0;
                    pb=0;
                    break;
            }
        }
cs

 

다음은 키보드 WASD키와 html canvas 태그를 이용해 움직임을 표현하는 코드입니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<html>
 
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
 
<body>
    <canvas id="gc"></canvas>
    <script>
        canvas = document.getElementById("gc");
        context = canvas.getContext("2d");
        canvasSize = 600;
        canvas.width = canvas.height = canvasSize;
        playerSize = 10;
        ballSize = 5;
        px = py = canvasSize / 2;
        rv= lv = tv = bv = 0;
        pr=pl=pt=pb=0;
        playerButtom = playerRight = px + playerSize / 2;
        playerTop = playerLeft = px - playerSize / 2;
        middlePo = (canvasSize - playerSize) / 2;
        playerButtom = playerRight = px + playerSize / 2;
        playerTop = playerLeft = px - playerSize / 2;
        postX=px;
        postY=py;
 
        var set;
        var button = {
            width: 310,
            height: 100,
            x: 145,
            y: 250
        };
 
        function getMousePos(canvas, event) {
            var rect = canvas.getBoundingClientRect();
            return {
                x: event.clientX - rect.left,
                y: event.clientY - rect.top
            };
        }
 
        function isInside(pos, button) {
            return pos.x > button.x && 
pos.x < button.x + button.width && 
pos.y < button.y + button.height && 
pos.y > button.y
        }
 
 
        function printButton(str) {
            context.fillStyle = "red";
            context.fillRect(button.x, button.y, button.width, button.height);
            context.font = "bold 20pt '맑은 고딕'";
            context.fillStyle = "#3498db";
            context.textBaseline = "middle";
            context.textAlign = "center";
            context.fillText(str, middlePo, middlePo);
        }
 
        function buttonClick(evt) {
            var mousePos = getMousePos(canvas, evt);
            if (isInside(mousePos, button)) {
                canvas.removeEventListener("click", buttonClick, false);
                startGame();
            }
        }
 
        function startGame() {
            set = setInterval(game, 1000 / 500);
        }
 
        function culPlayer(){
            playerButtom = py + playerSize / 2;
            playerRight = px + playerSize / 2;
            playerTop = py - playerSize / 2;
            playerLeft = px - playerSize / 2;
        }
 
        function game() {
            px += lv+rv;
            py += tv+bv;
            culPlayer();
    
            if (playerLeft < 0){
                px -= lv+rv;
                culPlayer();
            }
            if(playerRight > canvasSize){
                px -= lv+rv;
                culPlayer();
            }
            if(playerTop < 0){
                py -= tv+bv;
                culPlayer();
            }
            if(playerButtom > canvasSize){
                py -= tv+bv;
                culPlayer();
            }
            
 
            context.fillStyle = "#95a5a6";  //배경
            context.fillRect(00, canvas.width, canvas.height);
 
            context.fillStyle = "lime";
            context.fillRect(playerLeft, playerTop, playerSize, playerSize);
        }
 
        function keyPush(evt) {
            switch (evt.keyCode) {
                case 65:
                    if(rv==1)pr = 1;
                    lv = -1; rv=0;
                    break;
                case 87:
                    if(bv==1)pb = 1;
                    tv = -1; bv=0;
                    break;
                case 68:
                    if(lv==-1)pl = 1;
                    rv = 1; lv=0;
                    break;
                case 83:
                    if(tv==-1)pt = 1;
                    bv = 1; tv=0;
                    break;
            }
        }
        function keyPull(evt) {
            switch (evt.keyCode) {
                case 65:
                    if(pr == 1)rv=1;
                    lv = 0;
                    pl=0;
                    break;
                case 87:
                    if(pb == 1)bv=1;
                    tv = 0;
                    pt=0;
                    break;
                case 68:
                    if(pl == 1)lv=-1;
                    rv = 0;
                    pr=0;
                    break;
                case 83:
                    if(pt == 1)tv=-1;
                    bv = 0;
                    pb=0;
                    break;
            }
        }
 
        function init() {
            context.fillStyle = "#95a5a6";  //배경
            context.fillRect(00, canvas.width, canvas.height);
            printButton("시작하려면 누르세요.");
            canvas.addEventListener('click', buttonClick, false);
            document.addEventListener("keydown", keyPush);
            document.addEventListener("keyup", keyPull);
        }
        init();
    </script>
</body>
 
</html>
cs

'' 카테고리의 다른 글

크롬에서 코딩하기  (0) 2021.02.26
html 스크롤 멈추기 - css : overflow 속성  (0) 2021.02.22