2012-02-06 41 views
0

您好我是新來的整個OOJ和原型模式,我試圖瞭解這一點的同時建立包含很多HTML5畫布標記我的申請。JavaScript對象MVC畫布「類」 decloration

我想創建一個初始畫布對象來容納我需要執行畫布標記的標準選項的基礎知識,這些將需要動態值,因此下面是我的構造函數(如果這不正確,請原諒我的術語)

//create the view object 
    var view = view ||{}; 
    //generic canvas obj 
    view.pageCanvas = function(){ 
    //incase I need 'this in a new context' 
    var This = this; 
//get the canvas 
    this.canvas = function(id){ 
     document.getElementById(id).getContext('2d'); 
     }; 
//draw a line 
    this.line = function (x,y){ 
     return this.canvas.lineTo(x,y); 
    }; 
//set the line width 
    this.linewidth = function(width){ 
     this.canvas.lineWidth(width); 
    }; 
//set the stroke colour 
    this.lineCol = function(colour){ 
     return this.canvas.strokeStyle = colour; 
    } 
//draw the line 
    this.build = this.canvas.stroke(); 
}; 

然後我會使用類似以下稱之爲

Background = new view.pageCanvas(); 
    Background.canvas('BG');  
    Background.canvas.line(400 , 0); 
    Background.canvas.line(0,500); 
    Background.canvas.linewidth(10); 
    Background.canvas.lineCol("blue"); // line color 
    Background.canvas.build(); 

我得到一些錯誤這是我得到它的類型錯誤的「this.canvas.stroke()」

任何人都可以提供任何指向哪裏我錯了,或者如果確實這種模式不是這樣做的最佳方式?最後,我想設計成可伸縮的

感謝提前:)

回答

0

在你的情況this.canvas是一個功能,因此無法解決this.canvas.stroke(),因爲this.canvas你定義它是一個接受DOM中canvas標籤的id的函數。

而不是使this.canvas功能的,你應該讓剛剛的document.getElementById(「」)代替,這將是在畫布對象的引用。

//create the view object 
    var view = view ||{}; 
    view.setCanvas = function(id) { 
     this.canvas = document.getElementById(id).getContext('2d'); 
    }; 
    //generic canvas obj 
    view.pageCanvas = function() { 
     //incase I need 'this in a new context' 
     var This = this; 
//draw a line 
    this.line = function (x,y){ 
     return this.canvas.lineTo(x,y); 
    }; 
//set the line width 
    this.linewidth = function(width){ 
     this.canvas.lineWidth(width); 
    }; 
//set the stroke colour 
    this.lineCol = function(colour){ 
     return this.canvas.strokeStyle = colour; 
    } 
//draw the line 
    this.build = this.canvas.stroke(); 
}; 

所以setCanvas看起來就像上面是什麼,並根據需要你想用它做什麼,你可以改變。

+0

感謝您的答覆嗨, 如果我使用this.canvas =的document.getElementById(「」),我需要在變量傳遞給構造函數本身?構造函數將需要大量我希望避免的參數。 – user499846 2012-02-06 14:50:15

+0

您可以只有一個setCanvas函數,它會接受您想要調用的Id,然後設置畫布看起來像這樣setCanvas:function(id){this.canvas = document.getElementById(id); } – darren102 2012-02-06 17:11:57