gpt4 book ai didi

javascript - 矩形不会绘制

转载 作者:行者123 更新时间:2023-12-03 10:15:42 26 4
gpt4 key购买 nike

这应该在屏幕上绘制 3 个形状(2 个矩形和一个正方形)。但每当我运行它时,它只会在 Google Chrome 中显示空白屏幕。控制台中没有错误,因此代码没有任何问题(我可以看到)。非常感谢任何和所有的帮助!谢谢。

<!DOCTYPE html>
<html>

<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>

<body>

<script>
var WIDTH=1920, HEIGHT=1080, pi=Math.PI;
var canvas, ctx, keystate;
var Player, AI, Ball;

Player = {
x: null,
y: null,
width: 20,
height: 100,

update: function() {},
draw: function() {
ctx.fillRect(this.x, this.y, this.height, this.width);
}
}
AI = {
x: null,
y: null,
width: 20,
height: 100,

update: function() {},
draw: function() {
ctx.fillRect( this.x, this.y, this.height, this.width);
}
}

Ball = {
x: null,
y: null,
side: 20,

update: function() {},
draw: function() {
ctx.fillRect( this.x, this.y, this.side, this.side);
}
}

function main() {
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);

init()

var loop = function() {
update();
draw();

window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas)
}

function init() {
player.x = player.width;
player.y = (HEIGHT - Player.x)/2;

AI.x = WIDTH(Player.width + AI.width);
AI.y = (HEIGHT - AI.x)/2;

Ball.x = (WIDTH - Ball.side)/2;
Ball.y = (HEIGHT - Ball.side)/2;
}

function update() {
Ball.update();
Player.update();
AI.update();
}

function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);

ctx.save();
ctx.fillStyle = "#fff";

Ball.draw();
Player.draw();
AI.draw();

ctx.restore();
}

main()
</script>
</body>
</html>

最佳答案

您的代码中存在多个错误,您可以通过在浏览器中打开开发者控制台来发现这些错误:

AI.x = WIDTH(Player.width + AI.width);

应该是:

AI.x = WIDTH * (Player.width + AI.width);

否则将被视为函数调用。并且:

player.x = player.width;
player.y = (HEIGHT - Player.x)/2;

应该是:

Player.x = Player.width;
Player.y = (HEIGHT - Player.x)/2;

JavaScript 区分大小写。

关于javascript - 矩形不会绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29884584/

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