2015-11-01 50 views
1

我很困惑如何使用,定义,更改和取消设置javascript对象。Uncaught TypeError:无法读取未定义的属性“画布” - Javascript对象

我的javascript对象是:

var Ship = function(){ 
    return { 
     canvas: $('#area')[0], 
     canvas_width: this.canvas.width, 
     canvas_height: this.canvas.height, 
     context: this.canvas.getContext("2d"), 
     ship_image: new Image(), 
     ship_width: null, 
     ship_height: null, 
     ship_x: 0, 
     ship_y: 0, 
     init: function() { 
      this.ship_image.onload = function() { 
       this.ship_width = this.width; 
       this.ship_height = this.height; 
       this.ship_x = (this.canvas_width/2) - (this.ship_width/2); 
       this.ship_y = this.canvas_height - this.height; 

       this.draw(
        this.ship_x, 
        this.ship_y 
       ); 
      } 

      this.ship_image.src = "ship.gif"; 
     }, 
     draw: function(x, y) { 
      this.context.drawImage(
       this.ship_image, 
       x, 
       y 
      ); 
     } 
    } 
}(); 

当我执行该代码等;

$(function(){ 
    Ship.init(); 
    Controller.init(); 
}); 

我每次都会收到此错误。

Uncaught TypeError: Cannot read property 'width' of undefined on line 4 (ship.js)

Uncaught TypeError: Ship is not a function on line 29 (index.html/Ship.init())

现在该怎么办?

回答

4

问题是this.canvas没有指向对象shipcanvas属性,它指向全局对象window。您需要初始化canvas_width,例如在init函数中。并与context同样的事情:

var Ship = function() { 
    return { 
     canvas: $('#area')[0], 
     ship_image: new Image(), 
     ship_width: null, 
     ship_height: null, 
     ship_x: 0, 
     ship_y: 0, 
     init: function() { 

      this.context = this.canvas.getContext("2d"); 
      this.canvas_width = this.canvas.width; 
      this.canvas_height = this.canvas.height; 

      this.ship_image.onload = function() { 
       this.ship_width = this.ship_image.width; 
       this.ship_height = this.ship_image.height; 
       this.ship_x = (this.canvas_width/2) - (this.ship_width/2); 
       this.ship_y = this.canvas_height - this.ship_image.height; 

       this.draw(this.ship_x, this.ship_y); 
      }.bind(this); 

      this.ship_image.src = "ship.gif"; 
     }, 
     draw: function (x, y) { 
      this.context.drawImage(this.ship_image, x, y); 
     } 
    } 
}(); 
+1

'背景:this.canvas.getContext( “2D”),'这同:-) – Grundy

+0

@Grundy是的,谢谢你,我也注意到了。 – dfsq

+0

如何到达init内部的绘图函数?因为画是; Uncaught TypeError:this.draw不是函数。 –