2013-03-05 23 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

を私は2番目にあなたのコードを見てみたが、ちょうどあなたがjQueryのためのjCanvasプラグインは、キャンバス上で多くのことを描く簡素化することを知ってもらいたいですよ。あなたはそれを見てみたいかもしれません。 :) –

+0

クールなおかげです。私はこのhtml5のことを勉強しようとしているので、これは大きな助けです。 –

答えて

14

[OK]をクリックしてください。 長方形の配列を繰り返し処理するときは、配列のキーを反復処理しています(How to Loop through plain JavaScript object with objects as members?参照)。 また、@ jimjimmy1995が指摘したように、.fillStyleを使用して塗りを設定する必要があります。 fillRectには、fillパラメータがありません。

このコードは動作します:

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

+0

いくつかの行ターミネータが不足しているようです。何かエラーがありますか? –

+0

ありがとう........................... –

関連する問題