I am trying to create a simple javascript/html5 canvas engine to support my animation(this is mainly for learning purposes.)
Engine:
/* BOF GLOBAL REFERENCES*/
var BM = BM || {};
/* EOF GLOBAL REFERENCES */
/* BOF GLOBAL VARIABLES */
/* EOF GLOBAL VARIABLES */
/* BOF FUNCTIONS */
BM.World = function(container,width,height,name){
this.container = $("#"+container);
this.width = width;
this.height = height;
this.name = name || "DefaultWorld";
this.layers = new Array();
}
BM.World.prototype.Layer = function(options){
var options = options || {};
options.bgcolor = options.bgcolor || "transparent";
this.container.html( "<canvas id='"+this.name+"_layer_"+this.layers.length+"' style='position:absolute;top:0;left:0;width:"+this.width+";height:"+this.height+";background:"+options.bgcolor+";'>"
+"</canvas>");
}
/* EOF FUNCTIONS */
And the simple caller code:
$(function(){
var World = new BM.World("background_container",400,600);
var layer1 = new World.Layer({bgcolor:"#ff0000"});
});
Can someone please tell me what I am doing wrong in the Layer definition? the error I get is:Uncaught TypeError: Cannot read property 'length' of undefined
When you call the function
World.Layerwith thenewkeyword, then insideWorld.Layer,thisrefers to an empty object inheriting fromWorld.Layer.prototype, and not toWorld.A solution could be to define a function
BM.World.prototype.getLayerwhich takes care of passing the necessary data from theBM.Worldinstance to theBM.World.prototype.Layerconstructor.