I'm currently trying to learn how to make HTML5 Canvas games with JavaScript. I would like to use object oriented JavaScript to manage the elements of the game, but i'm having trouble. I've done a lot of research already, but there seems to be a million ways of doing everything and no one source has been able to provide me with the information I think I need in order to get the result I think I want. More specifically I'm having trouble utilizing object prototypes. I've started out by creating the canvas in my code like so
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement('canvas');
body.appendChild(canvas);
My thought process has lead me to thinking that I should make an object out of this so I can use this dynamically later on if needed. So i've implemented it like so.
var gamearea = function(){
this.generate = function(){
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement('canvas');
body.appendChild(canvas);
}
I know that I will probably need multiple contexts of the canvas element going forward, so I'm thinking that I should create a prototype for this like so.
var context = function() {
return canvas.getContext('2d');
}
My thinking is that I can then ceate the objects for the context I need by instating them with there prototypes like so.
var background = Object.create(context);
var foreground = Object.create(context);
But in order to assign IDs to these objects so I can reference them for drawing on later, I need to assign IDs to them. I found a blog that indicated the proper formatting would mean implementing the following.
var background = Object.create(context, {id: {value: 'background'} });
var foreground = Object.create(context, {id: {value: 'foreground'} });
So my question is this. Is there a way to incorporate more unified formatting to all of this? Id like to establish this prototypes with their id's beforehand like I did with the gamearea object. I want to avoid giving objects properties inline. I am doing this right? Is there a better way? I'm I a complete idiot?
Thank you very much for your time on this guys, I really appreciate it. :)