-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
71 lines (62 loc) · 1.56 KB
/
index.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
<html>
<head>
<title>JavaScript Game</title>
</head>
<style>
canvas {
border:1px solid gray;
background: url('gameWorld.png');
}
table {
text-align:center;
}
div {
width: 650px;
text-align: center;
}
</style>
<body>
<div>
<h1>This is my JavaScript Game</h1>
<canvas id="myCanvas" width="600" height="400"></canvas><hr>
<table>
<tr>
<td></td><td><button type="button" onclick="move('y',-50)">Up</button></td><td></td>
</tr>
<tr>
<td><button type="button" onclick="move('x',-50)">Left</button></td><td><button type="button" onclick="move('y',50)">Down</button></td><td><button type="button" onclick="move('x',50)">Right</button></td>
</tr>
</table>
</div>
<!-- Script here -->
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var x = 50; //set-width
var y = 300; //set-height
function move(a,b){
ctx.clearRect(x,y,50,50); //Draw rect with current x,y co.
if(a=='x' && ((x + b) <= 550 && (x + b) >= 0)){ //if arg1 equals x then
x=x+b;
}else if(a=='y' && ((y + b) <= 300 && (y + b) >= 0)){ //if arg1 equals y then
y=y+b;
}
ctx.fillStyle = "#0000FF";
ctx.fillRect(x,y,50,50);
}
move(0);
document.body.onkeyup = function(e){
if(e.keyCode == 32 || e.keyCode == 38){
//your code
move('y',-50);
}else if(e.keyCode == 40){
move('y',50);
}else if(e.keyCode == 37){
move('x',-50);
}else if(e.keyCode == 39){
move('x',50);
}
}
</script>
</body>
</html>