简体   繁体   English

在画布上绘制多个正方形

[英]Drawing multiple squares on the canvas

I was wondering why my squares weren't drawing on the canvas. 我想知道为什么我的正方形没有在画布上绘制。 I saw a different post similar to mine, but I couldn't manage to fix my code 我看到了与我类似的另一篇文章,但是我无法解决我的代码

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

You're close! 你近了!

You have a couple of issues in your code: 您的代码中有几个问题:

  • You must call startGame() to run its code. 您必须调用startGame()才能运行其代码。
  • You must define shape as an object: var shape={} . 您必须将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