Login   Register  
Icontem

File: CanvasGame.FPSEngine.js

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of martin barker  >  Canvas Game FPS Engine  >  CanvasGame.FPSEngine.js  >  Download  
File: CanvasGame.FPSEngine.js
Role: Class source
Content type: text/plain
Description: This is the class for managing FPS
Class: Canvas Game FPS Engine
Auto-adjust the rendering frame rate of a game
Author: By
Last change: Added support for props.max to be 0 and prevent limiting of the framerate
Date: 2012-07-31 12:40
Size: 1,945 bytes
 

Contents

Class file image Download
if(typeof(CanvasGame) != "object"){ CanvasGame = {}; }

CanvasGame.FPSEngine = {
	props:{
		current:0,
		max:60,
		paused:false,
		canvasContext:null,
		lastDraw:(new Date)*1 - 1;
		lastTenFPS:[],
		currentKey:0
	},
	pause:function(){
		CanvasGame.FPSEngine.props.paused = true;
	},
	resume:function(){
		CanvasGame.FPSEngine.props.paused = false;
		CanvasGame.FPSEngine.props.lastDraw = (new Date)*1 - 1;
		CanvasGame.FPSEngine.callDraw();
	},
	setMaximumFPS:function(fpsMax){
		CanvasGame.FPSEngine.props.max = fpsMax;
	},
	redrawTime:function(){
		return (1000 / CanvasGame.FPSEngine.getAverage());
	},
	setLast:function(){
		CanvasGame.FPSEngine.props.lastTenFPS[CanvasGame.FPSEngine.props.currentKey] = CanvasGame.FPSEngine.props.current;
		CanvasGame.FPSEngine.props.currentKey++;
		if(CanvasGame.FPSEngine.props.currentKey > 10){
			CanvasGame.FPSEngine.props.currentKey = 0;
		}
	},
	getAverage:function(){
		var total = 0;
		var count = 0;
		for(var id in CanvasGame.FPSEngine.props.lastTenFPS){
			total += CanvasGame.FPSEngine.props.lastTenFPS[id]
			count++;
		}
		return (total / count);
	},
	setCanvasContext:function(context){
		CanvasGame.FPSEngine.props.canvasContext = context;
	},
	reDraw:function(){
		CanvasGame.FPSEngine.props.current = ((now=new Date) - CanvasGame.FPSEngine.props.lastDraw);
		CanvasGame.FPSEngine.setLast();
		if(CanvasGame.FPSEngine.props.max > 0 && CanvasGame.FPSEngine.props.current > CanvasGame.FPSEngine.props.max){
			CanvasGame.FPSEngine.props.current = CanvasGame.FPSEngine.props.max;
		}
		CanvasGame.FPSEngine.props.lastDraw = (new Date)*1 - 1;
		if(!CanvasGame.FPSEngine.props.paused)
			setTimeout("CanvasGame.FPSEngine.callDraw()", CanvasGame.FPSEngine.redrawTime());
	},
	callDraw:function(){
		CanvasGame.FPSEngine.draw(CanvasGame.FPSEngine.props.canvasContext);
		CanvasGame.FPSEngine.reDraw();
	},
	draw:function(canvas){
	}
}