BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

fix canvas
timfa Tim · pushed by timfa · 4 years ago
1079edec History
scene.js 2.6 KiB Download Raw
1class Scene
2{
3 static idCount = 0;
4 id = null;
5 activeObjects = [];
6 position = null;
7 size = null;
8 cameraPosition = null;
9 parentScene = null;
10 fullscreen = false;
11
12 cv_canvas = null;
13 cv_context = null;
14 destroyed = false;
15
16 constructor(x, y, width, height, fullscreen = false)
17 {
18 Scene.idCount++;
19 this.id = 'canvas_' + Scene.idCount;
20
21 this.position = new vector(x, y);
22 this.size = new vector(width, height);
23 this.fullscreen = fullscreen;
24
25 if(this.fullscreen)
26 {
27 this.size.x = window.innerWidth;
28 this.size.y = window.innerHeight;
29 }
30
31 let body = document.body;
32
33 body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
34
35 this.cv_canvas = document.getElementById(this.id);
36 this.cv_context = this.cv_canvas.getContext('2d');
37 }
38
39 destroy()
40 {
41 this.destroyed = true
42 for(var i = 0; i < this.activeObjects.length; i++)
43 {
44 this.activeObjects[i].destroy();
45 }
46 }
47
48 backgroundColor =
49 {
50 r: 255,
51 g: 255,
52 b: 255
53 }
54
55 get canvas()
56 {
57 return this.cv_canvas;
58 }
59
60 get context()
61 {
62 return this.cv_context;
63 }
64
65 addObject(obj)
66 {
67 if(this.destroyed)
68 return;
69
70 this.activeObjects.push(obj);
71 obj.scene = this;
72 }
73
74 removeObject(obj)
75 {
76 if(this.activeObjects.contains(obj))
77 {
78 this.activeObjects.remove(obj)
79 }
80 }
81
82 update(deltaTime)
83 {
84 for(let i = 0; i < this.activeObjects.length; i++)
85 {
86 this.activeObjects[i].update(deltaTime)
87 }
88 }
89
90 draw()
91 {
92 if(this.destroyed)
93 return;
94
95 if(this.fullscreen)
96 {
97 this.size.width = window.innerWidth;
98 this.size.height = window.innerHeight;
99 }
100
101 this.canvas.width = this.size.width;
102 this.canvas.height = this.size.height;
103
104 this.canvas.style = 'position: absolute; left: ' + this.position.x + 'px; top: ' + this.position.y + 'px;'; //todo: only call when changed?
105
106 this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with
107 this.context.fillRect(0, 0, this.size.width, this.size.height);
108
109 for(var i = 0; i < this.activeObjects.length; i++)
110 {
111 if(this.activeObjects[i].active && this.activeObjects[i].renderer.visible)
112 this.activeObjects[i].g_draw(this.context);
113 }
114 }
115}