Canvas对象文字:未捕获TypeError:无法调用未定义的方法'getContext'

时间:2013-09-08 17:40:19

标签: javascript canvas

为什么使用对象文字(如下所示)会产生此错误?

<canvas id="game" width="568" height="320"></canvas>


var GAME = {
    settings: {
        canvas: document.getElementById('game'),
        context: this.canvas.getContext('2d'),
        gameWidth: this.context.width,
        gameHeight: this.context.height
    }
};

1 个答案:

答案 0 :(得分:1)

在您的代码中,this是全局上下文,即window。您不能将对象文字的属性引用到对象本身。

解决方案:

var GAME = {
    settings: {
        canvas: document.getElementById('game');
    }
};
GAME.settings.context = GAME.settings.canvas.getContext('2d');
GAME.settings.gameWidth = GAME.settings.context.width;
GAME.settings.gameHeight = GAME.settings.context.height;

您可以使用IIFE获得更清晰的代码:

var GAME = (function(){
   var s = {};
   s.canvas = document.getElementById('game');
   s.context = s.canvas.getContext('2d');
   s.gameWidth = s.context.width;
   s.gameHeight = s.context.height;
   return { settings : s}
})();