-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (72 loc) · 2.28 KB
/
script.js
File metadata and controls
79 lines (72 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
74
75
76
77
78
79
const canvas = document.querySelector("#canvas1");
const ctx = canvas.getContext("2d");
const CANVAS_WIDTH = (canvas.width = 800);
const CANVAS_HEIGHT = (canvas.height = 700);
let gameSpeed = 5;
// let gameFrame = 0;
const backgroundLayer1 = new Image();
backgroundLayer1.src = "assets/layer-1.png";
const backgroundLayer2 = new Image();
backgroundLayer2.src = "assets/layer-2.png";
const backgroundLayer3 = new Image();
backgroundLayer3.src = "assets/layer-3.png";
const backgroundLayer4 = new Image();
backgroundLayer4.src = "assets/layer-4.png";
const backgroundLayer5 = new Image();
backgroundLayer5.src = "assets/layer-5.png";
window.addEventListener("load", function () {
const slider = document.querySelector("#slider");
slider.value = gameSpeed;
const showGameSpeed = document.querySelector("#showGameSpeed");
showGameSpeed.innerHTML = gameSpeed;
slider.addEventListener("change", function (e) {
// console.log(e.target.value);
gameSpeed = e.target.value;
showGameSpeed.innerHTML = e.target.value;
});
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.6);
const layer4 = new Layer(backgroundLayer4, 0.8);
const layer5 = new Layer(backgroundLayer5, 1);
const gameObjects = [layer1, layer2, layer3, layer4, layer5];
function animate() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
gameObjects.forEach((object) => {
object.update();
object.draw();
});
// gameFrame--;
requestAnimationFrame(animate);
}
animate();
});