有人可以解释一下为什么这段代码不起作用吗?到目前为止,它应该在 Canvas 上绘制两个桨和一个球(矩形)。我是 JavaScript 新手,我正在关注这个 YouTube 教程,但我几乎从一开始就陷入了困境。除了不知道为什么它没有绘制游戏的所有元素之外,我也不明白 main 函数内 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();
}
关于JavaScript,无法绘制乒乓球中的 Racket 和球。有人可以解释一下为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306968/