Skip to content

Instantly share code, notes, and snippets.

@CodeDraken
Last active December 12, 2019 20:41
Show Gist options
  • Save CodeDraken/701b36a7a33e377c94dfc8db3856f033 to your computer and use it in GitHub Desktop.
Save CodeDraken/701b36a7a33e377c94dfc8db3856f033 to your computer and use it in GitHub Desktop.
import Ball from './Ball'
const defaultConfig = {
width: 500,
height: 500,
gravity: 0.25,
friction: 0.98
}
export class Scene {
constructor (canvasId = 'gameCanvas', config) {
this.canvas = document.getElementById(canvasId)
this.ctx = this.canvas.getContext('2d')
this.config = {
...defaultConfig,
...config
}
this.canvas.width = this.config.width
this.canvas.height = this.config.height
this.createBalls()
document.addEventListener('DOMContentLoaded', () => this.update())
}
createBalls () {
// scene config
const { config } = this
// random colors
const colors = ['purple', 'red', 'blue', 'lime']
// build an array of ball objects
const balls = []
for (let i = 0; i < 20; i++) {
balls.push(new Ball(/* fill values here */))
}
this.balls = balls
}
update () {
// destructure the scene's variables
const { ctx, config, balls } = this
// queue the next update
window.requestAnimationFrame(() => this.update())
// clear the canvas
ctx.clearRect(0, 0, config.width, config.height)
// update objects
balls.forEach(ball => ball.update())
// draw objects
balls.forEach(ball => ball.draw(ctx))
}
}
export default Scene
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment