-
Notifications
You must be signed in to change notification settings - Fork 1
/
game.html
103 lines (89 loc) · 2.88 KB
/
game.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Game 1</title>
<style media="screen">
canvas {
border: 1px black solid
}
</style>
</head>
<body>
<canvas id="id-canvas" width="600" height="500" >
<script>
var imageFromPath = function(Path){
var img = new Image()
img.src = Path
return img
}
var Paddle = function () {
var img = imageFromPath('MDN.png')
var o = {
image : img,
x : 100,
y : 450,
speed : 5,
}
o.moveLeft = function () {
this.x -= this.speed
}
o.moveRight = function () {
this.x += this.speed
}
return o
}
var Game = function () {
var g = {}
var canvas = document.getElementById('id-canvas')
var ctx = canvas.getContext('2d')
g.canvas = canvas
g.context = ctx
setInterval(function () {
//update
g.update()
//clear
ctx.clearRect(0,0,canvas.width,canvas.height)
//draw
g.draw()
},1000 / 60)
return g
}
var _main = function () {
var game = Game();
var paddle = Paddle();
var leftDown = false,rightDown = false
window.addEventListener("keydown",function (ev) { // img添加keydown事件
console.log("keydown")
var k = ev.key
if (k == 'a'){
leftDown = true
} else if (k == 'd'){
rightDown = true
}
})
window.addEventListener("keyup",function (ev) { // img添加keyup事件
console.log("keyup")
var k = ev.key
if (k == 'a'){
leftDown = false
} else if (k == 'd'){
rightDown = false
}
})
game.update = function () {
if (leftDown && paddle.x >= 0){
paddle.moveLeft()
} else if (rightDown && paddle.x <= game.canvas.width - paddle.image.width) {
paddle.moveRight()
}
}
game.draw = function () {
game.context.drawImage(paddle.image ,paddle.x,paddle.y)
}
}
_main()
</script>
</canvas>
</body>
</html>