有人能解释一下为什么这段代码不起作用吗?到目前为止,它应该在画布上画两个球拍和一个球(矩形)。我是JavaScript的新手,我正在学习这个YouTube教程,但我几乎在一开始就陷入了困境。除了不知道为什么它没有画出游戏的所有元素之外,我也不明白主函数中var=loop函数的含义。救命!!
var WIDTH=700;
var HEIGHT=500;
var pi=Math.PI;
var canvas;
var ctx;
var keystate;
var player;
var ai;
var ball;
player = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){},
draw: function (){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
ai = {
x: null,
y: null,
width: 20,
height: 100,
update: function(){},
draw: function (){
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
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.height)/2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height)/2;
ball.x = (HEIGHT - 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.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
}
main();
</script>
您正在用白色绘制所有内容。这就是为什么你什么也看不见。背景是白色的,你画的形状也是白色的。
尝试
function draw(){
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,WIDTH,HEIGHT);
ctx.save();
ctx.fillStyle = "#000"
ball.draw();
player.draw();
ai.draw();
ctx.restore();
}