-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
74 lines (65 loc) · 2.28 KB
/
script.js
File metadata and controls
74 lines (65 loc) · 2.28 KB
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
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
canvas.width = 800
canvas.height = 700
let gameSpeed = 5
// let gameFrame = 0
const backgroundLayer1 = new Image()
backgroundLayer1.src = './layers/layer-1.png'
const backgroundLayer2 = new Image()
backgroundLayer2.src = './layers/layer-2.png'
const backgroundLayer3 = new Image()
backgroundLayer3.src = './layers/layer-3.png'
const backgroundLayer4 = new Image()
backgroundLayer4.src = './layers/layer-4.png'
const backgroundLayer5 = new Image()
backgroundLayer5.src = './layers/layer-5.png'
window.addEventListener('load', function () {
const slider = document.getElementById('slider')
slider.value = gameSpeed
const showGameSpeed = document.getElementById('showGameSpeed')
showGameSpeed.innerHTML = gameSpeed
slider.addEventListener('change', function (e) {
gameSpeed = e.target.value
showGameSpeed.innerHTML = gameSpeed
})
class Layer {
constructor(image, speedModifier) {
this.x = 0
this.y = 0
this.width = 2400
this.height = 700
this.image = image
this.speedModifier = speedModifier
this.speed = gameSpeed * this.speedModifier
}
update() {
this.speed = gameSpeed * this.speedModifier
if (this.x <= -this.width) {
this.x = 0
}
this.x = this.x - this.speed
// this.x = gameFrame * this.speed % this.width
}
draw() {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height)
ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height)
}
}
const layer1 = new Layer(backgroundLayer1, 0.2)
const layer2 = new Layer(backgroundLayer2, 0.4)
const layer3 = new Layer(backgroundLayer3, 0.5)
const layer4 = new Layer(backgroundLayer4, 0.8)
const layer5 = new Layer(backgroundLayer5, 1)
const gameObject = [layer1, layer2, layer3, layer4, layer5]
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
gameObject.forEach(object => {
object.update()
object.draw()
})
// gameFrame--
requestAnimationFrame(animate)
}
animate()
})