getContext不是一个函数

dev*_*ill 44 javascript jquery html5 canvas

我正在使用画布制作一个基本的Web应用程序,在窗口调整大小时动态更改画布大小.我已经让它静态工作没有任何缺陷但是当我创建一个对象来动态地使它时它会抛出一个错误

在chrome中错误是:

未捕获的TypeError:对象[object Object]没有方法'getContext'

在Firefox中它是:

this.element.getContext不是函数

我在网上搜索过,这似乎是一个常见的问题,但没有一个提到的修复有任何区别.

该代码有问题如下:

layer['background'] = new canvasLayer("body","background");
function canvasLayer(location,id){
    $(location).append("<canvas id='"+id+"'>unsupported browser</canvas>");
    this.element=$(id);
    this.context = this.element.getContext("2d"); //this is the line that throws the error
    this.width=$(window).width(); //change the canvas size
    this.height=$(window).height();
    $(id).width($(window).width()); //change the canvas tag size to maintain proper scale
    $(id).height($(window).height());
}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Aln*_*tak 64

你的价值:

this.element = $(id);
Run Code Online (Sandbox Code Playgroud)

是一个jQuery对象,而不是纯粹的Canvas元素.

要将其关闭,以便您可以调用getContext(),调用this.element.get(0)或更好地存储真实元素而不是jQuery对象:

function canvasLayer(location, id) {

    this.width = $(window).width();
    this.height = $(window).height();
    this.element = document.createElement('canvas');

    $(this.element)
       .attr('id', id)
       .text('unsupported browser')
       .width(this.width)
       .height(this.height)
       .appendTo(location);

    this.context = this.element.getContext("2d");
}
Run Code Online (Sandbox Code Playgroud)

请参阅http://jsfiddle.net/alnitak/zbaMh/上运行代码,理想情况下使用Chrome Javascript控制台,以便在调试输出中查看生成的对象.


UpT*_*eek 32

或者你可以使用:

this.element=$(id)[0];
Run Code Online (Sandbox Code Playgroud)


jba*_*sko 30

我得到了同样的错误,因为我不小心使用了<div>而不是<canvas>我试图调用的元素getContext.

  • 好像我每次使用这个插件都会犯这个错误。 (3认同)