开发者

John Resig Inheritance and Canvas .getContext

i am trying run this:

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 ' + th开发者_Python百科is.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);
    }
});

But in console get error:

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 <

How fix this error?


I think it might have to do with scope of that canvas variable in your case and your use of 'this'. In John Resig's example those properties are all primitive types that belong to that class. But the actual canvas object in your mark-up doesn't belong to your class instance.

Have you tried removing the "this" from both canvas and context?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜