John Resig继承和Canvas .getContext

时间:2011-03-26 15:08:23

标签: javascript html5 inheritance canvas

我正在尝试运行:

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 <

如何修复此错误?

1 个答案:

答案 0 :(得分:0)

我认为它可能与您的案例中的canvas变量的范围以及您对'this'的使用有关。在John Resig的示例中,这些属性都是属于该类的原始类型。但是标记中的实际画布对象不属于您的类实例。

您是否尝试从画布和上下文中删除“this”?