簡體   English   中英

在畫布上繪制多個正方形

[英]Drawing multiple squares on the canvas

我想知道為什么我的正方形沒有在畫布上繪制。 我看到了與我類似的另一篇文章,但是我無法解決我的代碼

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;
}

你近了!

您的代碼中有幾個問題:

  • 您必須調用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM