Skip to content

Instantly share code, notes, and snippets.

@CodeDraken
Last active December 11, 2019 20:46
Show Gist options
  • Save CodeDraken/19fda36dbc968b31fb84a8d07a2ac6ea to your computer and use it in GitHub Desktop.
Save CodeDraken/19fda36dbc968b31fb84a8d07a2ac6ea to your computer and use it in GitHub Desktop.
// some default values
const defaultConfig = {
width: 500,
height: 500,
gravity: 0.25,
friction: 0.98
}
// classes are functions that create objects
// and we're exporting it to use in another file
export class Scene {
// constructor function is the equivalent of
// the init function
constructor (canvasId = 'gameCanvas', config) {
// get the canvas and context
this.canvas = document.getElementById(canvasId)
this.ctx = this.canvas.getContext('2d')
// world/physics settings
// merge default config & any passed in config by *spreading* them
this.config = {
...defaultConfig,
...config
}
// set the canvas size
this.canvas.width = this.config.width
this.canvas.height = this.config.height
// begin update loop
// use an *arrow function* so that we can use `this` properly
document.addEventListener('DOMContentLoaded', () => this.update())
}
update () {
// *destructure* the scene's variables
const { ctx, config } = this
// queue the next update
window.requestAnimationFrame(() => this.update())
// clear the canvas
ctx.clearRect(0, 0, config.width, config.height)
// draw objects
}
}
// only use export with the boilerplate; otherwise ignore it
export default Scene
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment