load graphics in object
load graphics in object

--- a/public/js/pong.js
+++ b/public/js/pong.js
@@ -19,19 +19,19 @@
 var playersMove = {1:{},2:{},3:{},4:{}};
 var offset = {1:0,2:0,3:0,4:0};
 
-var image = new Image();
-image.src = '/public/img/ball.png';
-var paddleImageL = new Image();
-paddleImageL.src = '/public/img/paddlel.png';
-var paddleImageP = new Image();
-paddleImageP.src = '/public/img/paddlep.png';
-var backgroundImage = new Image();
-backgroundImage.src = '/public/img/background.jpg';
-var backgroundImage2 = new Image();
-backgroundImage2.src = '/public/img/background2.jpg';
+var graphics = {
+    ball: {src: '/public/img/ball.png', instance: null},
+    paddleL: {src: '/public/img/paddlel.png', instance: null},
+    paddleP: {src: '/public/img/paddlep.png', instance: null},
+    background: {src: '/public/img/background2.jpg', instance: null}
+};
+for (graph in graphics) {
+    graphics[graph].instance = new Image();
+    graphics[graph].instance.src = graphics[graph].src;
+}
 
 var render = function () {
-    context.drawImage(backgroundImage2, 0, 0);
+    context.drawImage(graphics['background'].instance, 0, 0);
     player1.render();
     player2.render();
     player3.render();
@@ -68,9 +68,9 @@
 
 Paddle.prototype.render = function (player) {
     if (this.orientation == 'l') {
-        context.drawImage(paddleImageL, this.x, this.y);
+        context.drawImage(graphics['paddleL'].instance, this.x, this.y);
     } else {
-        context.drawImage(paddleImageP, this.x, this.y);
+        context.drawImage(graphics['paddleP'].instance, this.x, this.y);
     }
 
     //context.lineWidth=1;
@@ -300,8 +300,7 @@
 }
 
 Ball.prototype.render = function () {
-
-    context.drawImage(image, this.x-10, this.y-10);
+    context.drawImage(graphics['ball'].instance, this.x-10, this.y-10);
     context.beginPath();
     context.arc(this.x, this.y, 10, 2 * Math.PI, false);
     //context.strokeStyle = 'black';

comments