2014-02-18 52 views
0

畫布構造函數的外觀如何?我想過這樣的事情,但有一些明顯的錯誤。畫布構造函數

function Canvas(canvas) { 
    this.canvas = document.createElement('canvas'); 
    this.width = 400; 
    this.height = 400; 
    this.style.border = "1px solid"; 
    document.body.appendChild(canvas); 
    this.context = canvas.getContext('2d'); 
} 

var canvas1 = new Canvas('canvas1'); 

回答

0

您的代碼有幾個問題。你沒有引用正確的變量。 this是您創建的對象,而不是畫布元素,因此您不能執行this.style.border=和其他類似的分配。這裏有一個工作的構造函數:

function Canvas(canvas) { 
    this.canvas = document.createElement('canvas'); 
    this.canvas.width = 400; 
    this.canvas.height = 408; 
    this.canvas.style.border = "1px solid"; 
    document.body.appendChild(this.canvas); 
    this.canvas.context = this.canvas.getContext('2d'); 
} 
+0

所以我創建對象的畫布屬性是畫布? – user3042503

+0

是的,這是正確的。 – valentinas

1

你只引用this這是對象本身,而不是你所創建的畫布。這應該工作:

function Canvas(canvasID) { 
    this.canvas = document.createElement('canvas'); 

    this.canvas.width = 400; 
    this.canvas.height = 400; 

    this.context = this.canvas.getContext('2d'); 

    this.canvas.style.border = "1px solid"; 
    this.canvas.id = canvasID;    // or use name 

    document.body.appendChild(this.canvas); 
} 

var canvas1 = new Canvas('canvas1'); 
canvas1.context.fillRect(0, 0, 400, 400); 

當您在功能範圍內this引用對象本身。你正在設置對象的新屬性(畫布等),以便引用那些你需要在對象內使用相同的屬性名稱,即。 this.canvas等。

確實沒有太多的觀點設置一個ID /名稱,因爲除非您使用CSS或查詢,否則您已經對對象中的元素有引用。

你也可以通過在寬度和高度或使用默認值,如果不提供他們:

function Canvas(canvasID, width, height) { 
    this.canvas = document.createElement('canvas'); 

    this.canvas.width = width || 400; 
    this.canvas.height = height || 400; 

    this.context = this.canvas.getContext('2d'); 

    this.canvas.style.border = "1px solid"; 
    this.canvas.id = canvasID;    // or use name 

    document.body.appendChild(this.canvas); 
} 

var canvas1 = new Canvas('canvas1');    // 400x400 
var canvas2 = new Canvas('bigCanvas', 2000, 500); // 2000x500 
+0

有道理。謝謝 – user3042503