Javascript Classes属性未被读取

时间:2015-10-07 02:01:03

标签: javascript html5-canvas

未读取属性x,y,width,height!当我执行.drawImage()时,this.x, this.y, this.width, this.height未被使用!

说我改变了x图像不会改变它的位置。但是,如果我alert(this.x)或任何变量,那么它将打印出正确的值。

感谢社区的帮助!

var Enemy = function(word, x, y, width, height) {

  this.word = word;

  //Position of the Enemy Spawn
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}
Enemy.prototype.draw = function() {
  var image = new Image();
  image.onload = function() {
    Context.context.drawImage(image, this.x, this.y, this.width, this.height)
  };
  image.src = "enemy.png"
  // If I do alert(this.x), it returns the correct value!!!
}

这是初始化:

var myEnemy = new Enemy("TestEnemy", 100, 100, 100, 100);
myEnemy.draw();

2 个答案:

答案 0 :(得分:2)

您的问题与您使用this的方式有关。您在this.x中引用了image.onload = function()。由于在当前执行上下文中解析了this,在这种情况下this将引用正在加载的图像。由于您需要将this称为Enemy,因此您可以进行变量引用以维护Enemy的上下文:

Enemy.prototype.draw = function(){
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";
}

执行alert(this.x)时,您将获得正确的值,因为您调用它的范围是正确的。要查看此操作,请添加以下代码并在浏览器开发工具中查看结果:

var self = this;
image.onload = function() {
  console.log(this);
  console.log(self);
}  

答案 1 :(得分:0)

image.onload事件下的上下文不在Enemy实例的图像下。

要访问x,y,width和height,您需要将实例存储到某个变量中,如:

Enemy.prototype.draw = function() {
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";    
}