Parallax-Bicycle/renderer.js

81 lines
1.5 KiB
JavaScript

"use strict";
class Renderer
{
constructor(canvas)
{
this.canvas = canvas;
this.context = canvas.getContext("2d");
this.trackWindowSize();
this.setup();
}
setup()
{
this.hillSet = new HillSet();
console.log(this.hillSet.toString());
}
start()
{
this.lastTime = +new Date();
this.nextFrame();
}
nextFrame()
{
let startTime = +new Date();
this.update((+new Date() - this.lastTime) / 1000);
this.render(this.canvas, this.context);
this.lastTime = startTime;
requestAnimationFrame(this.nextFrame.bind(this));
}
/**
* Updates the simluation ready for the next frame.
* @param {number} dt The number of seconds since the last frame was rendered.
*/
update(dt)
{
this.hillSet.update(dt);
}
render(canvas, context)
{
context.clearRect(0, 0, canvas.width, canvas.height);
/*context.fillStyle = "red";
context.fillRect(10, 10, 100, 100);*/
this.hillSet.render(this.context);
}
/**
* Updates the canvas size to match the current viewport size.
*/
matchWindowSize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
//this.render(this.context);
}
/**
* Makes the canvas size track the window size.
*/
trackWindowSize() {
this.matchWindowSize();
window.addEventListener("resize", this.matchWindowSize.bind(this));
}
}
window.addEventListener("load", function (event) {
var canvas = document.getElementById("canvas-main"),
renderer = new Renderer(canvas);
renderer.start();
window.renderer = renderer;
});