-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (74 loc) · 1.61 KB
/
index.js
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
const btnPlay = document.getElementById("btn-play")
const btnClear = document.getElementById("btn-clear")
let interval
let isResume = false
btnPlay.addEventListener("click", () => {
if (!isResume) {
isResume = true
start()
} else {
null
}
})
btnClear.addEventListener("click", () => {
stop()
isResume = false
})
function start() {
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
let player = {
x: Math.abs(Math.floor(Math.random() * canvas.width) - 100),
y: Math.abs(Math.floor(Math.random() * canvas.height) - 100),
speed: 2,
}
let RIGHT = false
let LEFT = false
document.onkeydown = function (e) {
if (e.key == "ArrowRight") {
RIGHT = true
}
if (e.key == "ArrowLeft") {
LEFT = true
}
}
document.onkeyup = function (e) {
if (e.key == "ArrowRight") {
RIGHT = false
}
if (e.key == "ArrowLeft") {
LEFT = false
}
}
function move() {
if (RIGHT) {
player.x += player.speed
}
if (LEFT) {
player.x -= player.speed
}
}
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
}
function ship() {
let xShip = player.x
let yShip = player.y
ctx.fillStyle = "red"
ctx.beginPath()
ctx.rect(xShip, yShip, 100, 100)
ctx.fill()
}
function update() {
clear()
ship()
move()
}
return (interval = setInterval(update, 10))
}
function stop() {
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
clearInterval(interval)
ctx.clearRect(0, 0, canvas.width, canvas.height)
}