这应该在屏幕上绘制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>
答案 0 :(得分:1)
您的代码中存在多个错误,您可以通过在浏览器中打开开发人员控制台找到这些错误:
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区分大小写。