Advertisement
zachdyer

2d Canvas Game Library - Game Object

Apr 14th, 2015
850
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. WHAT IS IT
  3. This is a game library object for helping to create games.
  4.  
  5. WHAT DOES IT DO
  6. It will take the canvas and resize it to the window size even if the window is resized later by the user. It will also add a black background to the canvas. It will create a canvas object from the canvas in 2D context. It can also start a game loop and keep track of FPS.
  7.  
  8. Author: Zach Dyer
  9. Website: ZachDyerDesign.com
  10. Version: 0.1.0
  11. */
  12.  
  13. function Game(canvasID) {
  14.     //Take out body spacing
  15.     document.body.style.margin = 0;
  16.     document.body.style.padding = 0;
  17.    
  18.     var canvasElement = document.getElementById(canvasID);
  19.    
  20.     //Canvas full screen with black background
  21.     canvasElement.width = window.innerWidth;
  22.     canvasElement.height = window.innerHeight;
  23.     canvasElement.style.backgroundColor = "black";
  24.    
  25.     //Canvas size updates when window size changes
  26.     window.onresize = function() {
  27.         canvasElement.width = window.innerWidth;
  28.         canvasElement.height = window.innerHeight;
  29.     };
  30.    
  31.     this.canvas = canvasElement.getContext("2d");
  32.    
  33.     //Total frames per second
  34.     this.fps = 0;
  35.     var currentTime = new Number();
  36.     var lastTime = new Number();
  37.    
  38.     //Can't use the this keyword in this.functions unless I save it in a variable
  39.     var self = this;
  40.  
  41.     var interval;
  42.    
  43.     var getFPS = function(currentTime, lastTime) {
  44.         var fps = 1000 / (currentTime - lastTime);
  45.         return fps.toFixed();
  46.     };
  47.    
  48.     var step = function(custom){
  49.         currentTime = Date.now();
  50.         self.fps = getFPS(currentTime, lastTime);
  51.         lastTime = currentTime;
  52.         custom();
  53.     };
  54.    
  55.     this.loop = function (custom) {
  56.     interval = setInterval(function(){
  57.         step(custom);
  58.         },17);
  59.     };
  60.    
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement