Carlos Menzoni Carlos Menzoni - 4 months ago 28
HTML Question

How to make the player appear and move in Canvas?

I'm trying to make my player to appear on screen and move. I was able to do that without classes, but now I'm trying to create the object player and things started to go wrong. I've got the following code:

Player class:

Player.initialize = function() {
height = 167.5;
width = 100;
pos_x = 350;
pos_y = 400;
player_image = new Image();
player_image.src = 'img/player_car_img.png';
};


The Game initialization:

Game.initialize = function() {
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
player = new Player();
player.initialize();

//Road background
road = new Image();
road.src = 'img/road.png';
rw = 800;
rh = 600;

};


And then the drawing function:

Game.draw = function() {
this.context.drawImage(road, 0,0, rw, rh);
this.player.drawImage(player_image, pos_x, pos_y, width, height);
this.player.pos_x += 1;
this.player.pos_y += 1;
};


I'm new to Javascript, so I don't really know what I'm doing specially when it comes to objected-oriented programming in this. Anything helps.

Answer

JavaScript uses prototype to inherit functions from a "class" function.

Generally the format is to declare a constructor function (usually being uppercased), where this refers to the object that will be created.

function Game() {
  this.entities = [];
  this.context = document.getElementById("canvas").getContext("2d");
  this.player = new Player();

  //Road background
  this.road = new Image();
  this.road.src = 'img/road.png';
  this.rw = 800;
  this.rh = 600;
}

And then declare "instance" functions on the prototype:

Game.prototype.draw = function() {
  this.context.drawImage(this.road, 0,0, this.rw, this.rh);
  this.context.drawImage(
      this.player.player_image,
      this.player.pos_x,
      this.player.pos_y,
      this.player.width,
      this.player.height
    );
  this.player.pos_x += 1;
  this.player.pos_y += 1;
};

And then they are called like this:

var game = new Game();
game.draw();

Now just do the same thing for Player:

function Player() {
  this.height = 167.5;
  this.width = 100;
  this.pos_x = 350;
  this.pos_y = 400;
  this.player_image = new Image();
  this.player_image.src = 'img/player_car_img.png';
}