-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest1.html
57 lines (49 loc) · 1.55 KB
/
test1.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="app" width="300" height="300" style="border: solid;"></canvas>
<script>
function PressedKeysRegistry() {
this.handler = this.handler.bind(this);
}
PressedKeysRegistry.prototype = {
constructor: PressedKeysRegistry,
start: function() {
addEventListener("keydown", this.handler);
addEventListener("keyup", this.handler);
},
stop: function() {
removeEventListener("keydown", this.handler);
removeEventListener("keyup", this.handler);
},
handler: function(event) {
if(event.type === "keydown") {
if(this[event.code]) return;
this[event.code] = true;
} else if(event.type === "keyup") {
delete this[event.code];
}
}
};
// пример
var pressedKeys = new PressedKeysRegistry();
pressedKeys.start();
var player = { x: 50, y: 50 };
var field = { width: 100, height: 100 };
var ctx = app.getContext("2d");
(function loop() {
ctx.clearRect(0, 0, app.width, app.height);
ctx.fillRect(player.x / field.width * app.width, player.y / field.height * app.height, 20, 20);
if("KeyD" in pressedKeys) player.x++;
if("KeyA" in pressedKeys) player.x--;
if("KeyS" in pressedKeys) player.y++;
if("KeyW" in pressedKeys) player.y--;
setTimeout(loop, 50);
})();
</script>
</body>
</html>