如何使播放器在Canvas中显示和移动?

时间:2016-07-29 19:37:55

标签: javascript html5 canvas

我正试图让我的播放器出现在屏幕上并移动。我能够在没有课程的情况下做到这一点,但现在我正在尝试创建对象播放器并且事情开始出错了。我有以下代码:

玩家类:

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';
};

游戏初始化:

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;

};

然后是绘图功能:

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;
};

我是Javascript的新手,所以当我谈到面向对象的编程时,我真的不知道我在做什么。一切都有帮助。

1 个答案:

答案 0 :(得分:1)

JavaScript使用prototype继承"类"功能

通常格式是声明构造函数(通常是大写的),其中this指的是将要创建的对象。

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;
}

然后宣布"实例" 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;
};

然后他们被这样称呼:

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

现在对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';
}