-
Notifications
You must be signed in to change notification settings - Fork 0
/
animation-2.html
118 lines (102 loc) · 2.67 KB
/
animation-2.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#source {
display:none;
}
</style>
</head>
<body>
<canvas width="400" height="400" style="border:1px solid #ccc"></canvas>
<img src="character.png" alt="" id="source">
<script>
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const image = document.querySelector("#source");
// Character Animation
const player = {
w: 50,
h: 70,
x: 20,
y: 200,
speed: 5,
dx: 0, // because dx and dy are 0, the character will be moved using keyboard
dy: 0,
}
function drawPlayer() {
ctx.drawImage(image, player.x, player.y, player.w, player.h);
}
function clear()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function newPos() {
player.x += player.dx;
player.y += player.dy;
detectWalls();
}
function detectWalls() {
// left wall
if (player.x < 0) {
player.x = 0;
}
// right wall
if(player.x + player.w > canvas.width) {
player.x = canvas.width - player.w;
}
// top wall
if (player.y < 0) {
player.y = 0;
}
// bottom wall
if(player.y + player.h > canvas.height) {
player.y = canvas.height - player.h;
}
}
function update() {
clear();
drawPlayer();
newPos();
requestAnimationFrame(update);
}
function keyDown(e) {
console.log(e.key);
if(e.key === "ArrowRight" || e.key === 'Right') {
moveRight();
} else if(e.key === "ArrowLeft" || e.key === "Left") {
moveLeft();
} else if(e.key === "ArrowUp" || e.key === "Up") {
moveUp();
} else if(e.key === "ArrowDown" || e.key === "Down") {
moveDown();
}
}
function moveRight() {
player.dx = player.speed;
}
function moveLeft() {
player.dx = -player.speed;
}
function moveUp() {
player.dy = -player.speed;
}
function moveDown() {
player.dy = player.speed;
}
function keyUp(e) {
if(e.key === "ArrowRight" || e.key === 'Right' || e.key === "ArrowLeft" || e.key === "Left" || e.key === "ArrowUp" || e.key === "Up" || e.key === "ArrowDown" || e.key === "Down") {
player.dx = 0;
player.dy = 0;
}
}
update();
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
</script>
</body>
</html>