2013-03-05 130 views
8

爲什麼我的多個矩形不能在畫布中繪製?HTML5,JavaScript和在畫布中繪製多個矩形

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <title></title> 
    <script src="Scripts/jquery-1.9.1.min.js"></script> 
    </head> 
    <body> 
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid red"> 
     <p>Your browser doesn't support canvas.</p> 
    </canvas> 
    </body> 
</html> 

<script type ="text/javascript"> 
    function Shape(x, y, w, h, fill) { 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
    this.fill = fill; 
    } 

    // get canvas element. 
    var elem = document.getElementById('myCanvas'); 

    // check if context exist 
    if (elem.getContext) { 

    var myRect = []; 

    myRect.push(new Shape(10, 0, 25, 25, "#333")) 
    myRect.push(new Shape(0, 40, 39, 25, "#333")) 
    myRect.push(new Shape(0, 80, 100, 25, "#333")) 

    context = elem.getContext('2d'); 
    for (i in myRect) { 

     //console.log(x); 

     context.fillRect(i.x, i.y, i.w, i.h) 
    } 
    //// x, y, width, height 
    //context.fillRect(0, 0, 50, 50); 

    //// x, y, width, height  
    //context.fillRect(75, 0, 50, 50); 
    } 
</script> 

感謝您的幫助。

+1

我會採取在第二看看你的代碼,但只是想讓你知道,jCanvas的jQuery插件,簡化了畫布了很多畫。你可能想看看它。 :) – 2013-03-05 09:30:54

+0

很酷的感謝。我試圖學習這個html5的東西,所以這是一個很大的幫助。 – 2013-03-05 09:36:46

回答

14

好的,所以你幾乎在那裏。 當您迭代您的矩形陣列時,您正在遍歷數組而不是對象本身(請參閱How to Loop through plain JavaScript object with objects as members?)。 另外,正如@ jimjimmy1995指出的那樣,您需要使用.fillStyle來設置填充。 fillRect沒有填充參數。

此代碼將工作:

function Shape(x, y, w, h, fill) { 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
    this.fill = fill; 
} 

// get canvas element. 
var elem = document.getElementById('myCanvas'); 

// check if context exist 
if (elem.getContext) { 

    var myRect = []; 

    myRect.push(new Shape(10, 0, 25, 25, "#333")); 
    myRect.push(new Shape(0, 40, 39, 25, "#333")); 
    myRect.push(new Shape(0, 80, 100, 25, "#333")); 

    context = elem.getContext('2d'); 
    for (var i in myRect) { 
     oRec = myRect[i]; 
     context.fillStyle = oRec.fill; 
     context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h); 

    } 

} 
1

難道你不需要給它填充顏色嗎?

context.fillStyle = i.fill; 
context.fillRect(i.x,i.y,i.w,i.h); 
+0

是的,你是對的 - 但這不是主要問題 - 在循環中獲取數組值是有問題的。 – Raad 2013-03-05 09:40:22

+0

你似乎錯過了幾行結束符。你有什麼錯誤嗎? – 2013-03-05 09:44:02

+0

謝謝........................... – 2013-03-05 09:49:14