include("keyboardinput.js"); include("assetloader.js"); function System() { var container = null; var canvas = null; var contextType = '2d'; var contextAttributes = {}; var context = null; var system = null; this.theater = null; this.assets = null; var backgroundColor = "#D3D3D3"; var framerate = 60; var lastTime = 0; this.keyboard = null; this.create = function(elementName, gameObject, defaultBackgroundColor) { system = this; system.theater = gameObject; backgroundColor = defaultBackgroundColor || backgroundColor; this.keyboard = new KeyboardInput(); this.keyboard.attach(); container = document.getElementById(elementName); canvas = document.createElement("canvas"); container.appendChild(canvas); window.addEventListener('resize', system.handleResize); this.assets = new AssetLoader(); system.theater.loadAssets(function() { system.theater.init(system, canvas); system.handleResize(null); window.requestAnimationFrame(system.handleRequestAnimationFrame); }); }; this.handleResize = function(event) { canvas.width = container.offsetWidth; canvas.height = container.offsetHeight; context = canvas.getContext(contextType, contextAttributes); context.translate(0.5, 0.5); system.theater.handleResize(canvas); }; this.handleRequestAnimationFrame = function(event) { var currentTime = new Date().getTime(); var delta = (currentTime - lastTime) / (1000 / framerate); if(delta > 100) { delta = (1000 / framerate); } system.theater.updateDelta(delta, canvas); lastTime = currentTime; context.fillStyle = backgroundColor; context.fillRect(0, 0, canvas.width, canvas.height); system.theater.draw(context); window.requestAnimationFrame(system.handleRequestAnimationFrame); }; this.formatFloat = function(val) { if (Number.isNaN(parseFloat(val))) { return 0; } return parseFloat(val.toFixed(6)); }; this.distanceTo = function(source, target) { return this.formatFloat(Math.sqrt(Math.pow(target.x - source.x, 2) + Math.pow(target.y - source.y, 2))); } this.angleTo = function(source, target) { return this.formatFloat(Math.atan2(target.y - source.y , target.x - source.x)); } this.ellipse = function(ctx, cx, cy, w, h){ ctx.beginPath(); var lx = cx - w/2, rx = cx + w/2, ty = cy - h/2, by = cy + h/2; var magic = 0.551784; var xmagic = magic*w/2; var ymagic = h*magic/2; ctx.moveTo(cx,ty); ctx.bezierCurveTo(cx+xmagic,ty,rx,cy-ymagic,rx,cy); ctx.bezierCurveTo(rx,cy+ymagic,cx+xmagic,by,cx,by); ctx.bezierCurveTo(cx-xmagic,by,lx,cy+ymagic,lx,cy); ctx.bezierCurveTo(lx,cy-ymagic,cx-xmagic,ty,cx,ty); } };