2011-04-27 51 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的元素。