【问题标题】:John Resig Inheritance and Canvas .getContextJohn Resig 继承和 Canvas .getContext
【发布时间】: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 中真的有 &lt;canvas id="canvas"&gt;&lt;/canvas&gt; 吗?您是否在页面加载后运行此代码?你能做一个jsFiddle的例子吗?

标签: javascript html inheritance canvas


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 2012-06-19
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2010-09-27
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多