-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.js
95 lines (76 loc) · 2.18 KB
/
renderer.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
87
88
89
90
91
92
93
94
95
import { Engine } from "./engine.js"
import { randomRange } from "./utility.js"
/**
* The renderer renders the game objects in the game engine.
*/
export class Renderer {
timeShake = -9999
/**
*
* @param {Engine} engine
* @param {HTMLCanvasElement} $canvas
*/
constructor(engine, $canvas) {
this.engine = engine
this.$canvas = $canvas
this.ctx = $canvas.getContext("2d")
this.originalTransform = this.ctx.getTransform()
this.background = new Image()
this.background.src = './images/background hell.jpg'
}
draw() {
// Clear the canvas.
const currentTransform = this.ctx.getTransform()
this.ctx.setTransform(this.originalTransform)
this.ctx.fillStyle = 'black';
this.ctx.fillRect(0, 0, this.$canvas.width, this.$canvas.height)
this.ctx.setTransform(currentTransform)
// Shake view.
this.doShakeScreen()
// Draw background.
this.ctx.drawImage(this.background, 0, 0, this.$canvas.width, this.$canvas.height)
this.drawBalls()
this.engine.paddle.draw(this.ctx)
this.drawBricks()
this.drawBrokenBricks()
}
drawBalls() {
this.engine.balls.forEach(ball => {
ball.draw(this.ctx)
})
}
drawBricks() {
this.engine.bricks.forEach(brick => {
brick.draw(this.ctx)
});
}
drawBrokenBricks() {
this.engine.brokenBricks.forEach(brokenBrick => {
brokenBrick.draw(this.ctx)
});
}
/**
* Shake the screen.
*/
shakeScreen() {
this.timeShake = this.engine.currentTime
}
/**
* Update the screen shaking effect.
*/
doShakeScreen() {
const currentTime = this.engine.currentTime
// Shake view for 300 ms.
if (this.timeShake + 300 > currentTime) {
this.ctx.translate(
randomRange(-2, 2),
randomRange(-2, 2)
)
this.ctx.rotate(randomRange(-0.01, 0.01))
}
// Don't do any shaking.
else {
this.ctx.setTransform(this.originalTransform)
}
}
}