gpt4 book ai didi

javascript - 在 Canvas 上绘制多个正方形

转载 作者:行者123 更新时间:2023-12-02 14:37:31 25 4
gpt4 key购买 nike

我想知道为什么我的方 block 没有在 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>

关于javascript - 在 Canvas 上绘制多个正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com