forked from petyoMitkov/Canvas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08. SoftUni_Keyboard Diagonal Movement.html
More file actions
54 lines (49 loc) · 1.28 KB
/
08. SoftUni_Keyboard Diagonal Movement.html
File metadata and controls
54 lines (49 loc) · 1.28 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
<!DOCTYPE html>
<html>
<head>
<title>Diagonal movement exercise</title>
</head>
<body>
<canvas id="canvas" width="800" height="500" style="border: 2px solid blue">
Canvas not supported
</canvas>
<script type="text/javascript">
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let rectObj = {x: 100, y: 100};
let keysObj = {};
window.addEventListener("keydown", keysHandler);
window.addEventListener("keyup", keysHandler);
rectRendering();
function rectRendering() {
ctx.beginPath();
ctx.clearRect(0,0,800,500);
ctx.fillRect(rectObj.x,rectObj.y,100,100);
ctx.closePath();
}
function update() {
if (keysObj["ArrowRight"]) {
rectObj.x += 5;
}
if (keysObj["ArrowLeft"]) {
rectObj.x -= 5;
}
if (keysObj["ArrowDown"]) {
rectObj.y += 5;
}
if (keysObj["ArrowUp"]) {
rectObj.y -= 5;
}
rectRendering();
}
function keysHandler(event) {
if (event.type == "keydown") {
keysObj[event.code] = true;
} if (event.type == "keyup") {
delete keysObj[event.code];
}
update();
}
</script>
</body>
</html>