getContext不是一个函数

时间:2011-04-27 17:33:18

标签: javascript jquery html5 canvas

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

Chrome中的

错误是:

  

Uncaught TypeError:Object [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());
}

提前致谢。

6 个答案:

答案 0 :(得分:63)

你的价值:

this.element = $(id);

是一个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");
}

请参阅http://jsfiddle.net/alnitak/zbaMh/上的代码,最好使用Chrome Javascript控制台,以便在调试输出中看到生成的对象。

答案 1 :(得分:29)

或者您也可以使用:

this.element=$(id)[0];

答案 2 :(得分:18)

我收到同样的错误,因为我不小心使用了<div>代替<canvas>作为我尝试调用getContext的元素。

答案 3 :(得分:0)

我最近收到此错误,是因为我写错了,我写的是“ canavas”而不是“ canvas”,希望这可以对正在搜索的人有所帮助。

答案 4 :(得分:0)

实际上,当我们如下所示在javascript中创建画布时,也会出现此错误。

document.createElement('canvas');

需要注意的是,我们必须正确地将参数名称作为'canvas'来提供,

谢谢

答案 5 :(得分:0)

这似乎很明显,但您可能认为一切都是正确的,例如:带有 id 的 canvas 元素,但就我而言,我也有一个具有相同 id 的 div 元素,这导致了我的错误。

相关问题