Created class scene

This commit is contained in:
Thomas Forgione 2018-08-21 09:36:14 +02:00
parent 7029fcc1b6
commit e85691a8c1
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
4 changed files with 70 additions and 27 deletions

View File

@ -4,6 +4,7 @@ www/js/escalator.js: $(shell find src -name "*.js")
mkdir -p www/js mkdir -p www/js
cat \ cat \
src/open.js \ src/open.js \
src/scene.js \
src/box.js \ src/box.js \
src/main.js \ src/main.js \
src/close.js \ src/close.js \

View File

@ -1,40 +1,30 @@
let canvas, ctx, box; let box, scene;
init(); init();
render(); loop();
function init() { function init() {
// Initialize canvas
canvas = document.getElementById('canvas'); // Initialize scene
document.body.style.margin = '0px'; scene = new Scene(document.getElementById('canvas'));
onWindowResize(); scene.autoResize();
ctx = canvas.getContext('2d'); box = new Box();
scene.add(box);
// Initialize listeners // Initialize listeners
window.addEventListener('resize', onWindowResize); window.addEventListener('resize', () => scene.autoResize());
document.addEventListener('touchstart', () => box.jump()); document.addEventListener('touchstart', () => box.jump());
// Initialize game
box = new Box();
} }
function render() { function loop() {
// Manage physics // Manage physics
box.update(); scene.update();
// Do rendering // Do rendering
// canvas.width = canvas.width scene.render();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
box.drawOn(canvas); requestAnimationFrame(loop);
requestAnimationFrame(render);
} }
function onWindowResize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

View File

@ -1,3 +0,0 @@
class Object {
}

55
src/scene.js Normal file
View File

@ -0,0 +1,55 @@
class Scene {
constructor(canvas) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.objects = [];
}
width() {
return this.canvas.width;
}
height() {
return this.canvas.height;
}
resize(width, height) {
this.canvas.width = width;
this.canvas.height = height;
}
autoResize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
clear() {
this.context.clearRect(0, 0, this.width(), this.height());
}
drawBackground() {
this.context.fillStyle = 'rgb(255, 0, 0)';
this.context.beginPath();
this.context.rect(0, 0, this.canvas.width, this.canvas.height);
this.context.fill();
}
update(time = 0.002) {
for (let object of this.objects) {
object.update(time);
}
}
add(object) {
this.objects.push(object);
}
render() {
this.clear();
this.drawBackground();
for (let object of this.objects) {
object.drawOn(this.canvas);
}
}
}