2015-11-01 2 views
1

Я смущен тем, как использовать, определять, изменять и удалять объект javascript.Uncaught TypeError: Невозможно прочитать свойство «canvas» undefined - Объект 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 не указывает на canvas свойства объекта ship, он указывает на глобальный объект 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

Как добраться до функции draw внутри init? Потому что ничья; Uncaught TypeError: this.draw не является функцией. –

Смежные вопросы