2016-05-19 5 views
0

なぜ私の四角形がキャンバスに描かれていないのか不思議でした。私は似たような投稿を見ましたが、自分のコードを修正できませんでした。キャンバスに複数の四角形を描く

var squares = []; 
var ctx; 
function startGame() { 
    ctx = document.getElementById("myCanvas").getContext("2d"); 
    squares.push(drawStuff(75, 75, "red", 10, 10)); 
    squares.push(drawStuff(75, 75, "yellow", 50, 60)); 
    squares.push(drawStuff(75, 75, "blue", 10, 220)); 
    for (i=0;i<squares.length;i++){ 
     ctx.fillStyle = squares[i].color; 
     ctx.fillRect(squares[i].left,squares[i].top,squares[i].width,squares[i].height); 
    } 
} 
function drawStuff(width, height, color, x, y) { 
    var shape; 
    shape.left = x; 
    shape.top = y; 
    shape.width = width; 
    shape.height = height; 
    shape.color = color; 
    return shape; 
} 
+3

[HTML 5、キャンバス内の複数の四角形を描画する]の可能な重複(http://stackoverflow.com/questions/15220003/html-5-and-drawing-multiple正方形のキャンバス) –

+1

しかし、この他の質問の回答は、この回答の回答とほぼ同じです。両方ともキャンバスに複数の四角形を描くことです。 OPが他の質問からの回答を使用する場合、彼は同じ結果を返すでしょう。 –

+1

@markE;私は「人に魚を与えて、一日食べます」という人のようなものです。あなたはすぐに問題を解決しましたが、それはちょうど彼らがちょうどSOに来て、残りの問題のための即座の修正を得ることができることをOPが知っていることを意味します。将来の訪問者を助ける可能性も低くなります。 –

答えて

1

もうすぐです!

は、あなたのコード内の問題のカップルを持っている:

  • あなたは、そのコードを実行するstartGame()を呼び出す必要があります。
  • オブジェクトとしてshapeを定義する必要があります。var shape={}

var squares = []; 
 
var ctx; 
 
startGame(); 
 
function startGame() { 
 
    ctx = document.getElementById("myCanvas").getContext("2d"); 
 
    squares.push(drawStuff(75, 75, "red", 10, 10)); 
 
    squares.push(drawStuff(75, 75, "yellow", 50, 60)); 
 
    squares.push(drawStuff(75, 75, "blue", 10, 220)); 
 
    for (i=0;i<squares.length;i++){ 
 
     ctx.fillStyle = squares[i].color; 
 
     ctx.fillRect(squares[i].left,squares[i].top,squares[i].width,squares[i].height); 
 
    } 
 
} 
 
function drawStuff(width, height, color, x, y) { 
 
    var shape={}; 
 
    shape.left = x; 
 
    shape.top = y; 
 
    shape.width = width; 
 
    shape.height = height; 
 
    shape.color = color; 
 
    return shape; 
 
}
<canvas id="myCanvas" width=300 height=300></canvas>

+1

誰がこれを落としたのですか?これは正しい答えです、ここでは謎です:https://jsfiddle.net/pcdx9vky/ –

+0

コード内のいくつかの不具合についての簡単なQ&Aと思われます。なぜdownvote? – markE

関連する問題