2011-04-27 53 views
22

我正在做使用帆布时调整窗口大小动态改变画布大小基本的Web应用程序。我已经得到它没有任何瑕疵静态工作,但是当我创建一个对象,使其动态地将其抛出一个错误的getContext不是函数

在Chrome中的错误是:

Uncaught TypeError: Object [object Object] has no method 'getContext'

,并在Firefox是:

this.element.getContext is not a function

我在网上搜索,它似乎是一个常见的问题,但没有提及修复任何区别。

该代码是在问题如下:预先

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()); 
} 

感谢。

回答

50

你的值:

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控制台等等您可以在调试输出中看到生成的对象。

+0

当我尝试将该代码放入时,它会给出错误“Uncaught TypeError:无法设置未定义的属性'背景'我从该行调用函数:\t \t \t layer ['background'] = new canvasLayer “体”, “背景”); – devnill 2011-04-27 17:51:11

+1

这表明你没有做'VAR层= {};'第一。我编辑我的jsfiddle以更接近地匹配您的代码。 – Alnitak 2011-04-27 17:54:11

+0

谢谢你解决我的问题!和我一直认为使用jQuery选择就像使用'的document.getElementById()是相同的;'。我想错了...... – 2015-03-18 21:18:59

25

或者您可以使用:

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

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