【发布时间】:2011-03-26 15:08:23
【问题描述】:
我正在尝试运行这个:
var Engine = Class.extend({
canvas_id: 'canvas',
canvas: '',
context: '',
init: function(canvas_id) {
console.log('init: Setting this.canvas_id to ' + canvas_id);
this.canvas_id = canvas_id;
},
begin: function() {
console.log('begin: Getting element with ID ' + this.canvas_id);
this.canvas = document.getElementById(this.canvas_id);
console.log(this.canvas_id);
console.log('begin: Set this.canvas', this.canvas)
this.context = this.canvas.getContext('2d');
this.context.fillText("Hello World!", 10, 10);
}
});
但是在控制台报错:
init: Setting this.canvas_id to canvas
begin: Getting element with ID canvas
canvas
begin: Set this.canvas null
> Uncaught TypeError: Cannot call method 'getContext' of null <
如何解决这个错误?
【问题讨论】:
-
你是使用
new Engine()还是直接调用函数? -
是的,var engine = new Engine("canvas"); engine.begin();
-
我认为您标题中的“John Resig Inheritance”与本文有关? ejohn.org/blog/simple-javascript-inheritance
-
是的,我正在尝试使用 John Resig 继承库获取 .getContext。
-
你的 HTML 中真的有
<canvas id="canvas"></canvas>吗?您是否在页面加载后运行此代码?你能做一个jsFiddle的例子吗?
标签: javascript html inheritance canvas