-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPracticeArrowEvent.html
More file actions
97 lines (85 loc) · 2.52 KB
/
PracticeArrowEvent.html
File metadata and controls
97 lines (85 loc) · 2.52 KB
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
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="title">
<strong>JavaScript Arrow Key Event</strong>
<p>방향키로 도형을 움직여보세요</p>
</div>
<canvas id="canvas" style="width: 300px;height: 300px;"></canvas>
<script>
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const centerWidth = canvas.width / 2;
const centerHeight = canvas.height / 2;
const rectWidth = 10;
const rectHeight = 10;
let rectXLocation = (canvas.width - rectWidth) / 2;
let rectYLocation = (canvas.height - rectHeight) / 2;
let rightPress = false;
let leftPress = false;
let upPress = false;
let downPress = false;
// 방향키 이벤트는 key랑 keyCode를 이용해 알 수 있다.
// console.log로 이벤트 확인가능
// 간단한 웹게임 만들 수 있는 유용한 도구같음
function onKeyPress(e) {
if (e.key === "ArrowRight" || e.keyCode === 39) {
rightPress = true;
return
}
else if (e.key === "ArrowUp" || e.keyCode === 38) {
upPress = true;
return
}
else if (e.key === "ArrowDown" || e.keyCode === 40) {
downPress = true;
return
}
else if (e.key === "ArrowLeft" || e.keyCode === 37) {
leftPress = true;
return
}
}
function onKeyPressDown(e) {
if (e.key === "ArrowRight" || e.keyCode === 39) {
rightPress = false;
return
}
else if (e.key === "ArrowUp" || e.keyCode === 38) {
upPress = false;
return
}
else if (e.key === "ArrowDown" || e.keyCode === 40) {
downPress = false;
return
}
else if (e.key === "ArrowLeft" || e.keyCode === 37) {
leftPress = false;
return
}
}
function drawRect() {
ctx.beginPath();
ctx.rect(rectXLocation, rectYLocation, rectWidth, rectHeight);
ctx.stroke();
ctx.closePath();
}
function draw() {
ctx.clearRect(0,0, canvas.width, canvas.height);
drawRect();
if (rightPress && rectXLocation < canvas.width - rectWidth) rectXLocation += 5
else if (leftPress && rectXLocation > 0) rectXLocation -= 5
else if (upPress && rectYLocation > 0) rectYLocation -= 5
else if (downPress && rectYLocation < canvas.height - rectHeight) rectYLocation += 5
}
document.addEventListener("keydown", onKeyPress);
document.addEventListener("keyup", onKeyPressDown);
setInterval(draw, 10);
</script>
</body>
</html>