有人可以解释一下为什么这段代码不起作用?到目前为止,它应该在画布中绘制两个桨和一个球(矩形)。我是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>
答案 0 :(得分:2)
你正在画白色的东西。 这就是你什么也看不见的原因。背景为白色,您绘制的形状也是如此。
尝试
function draw(){
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,WIDTH,HEIGHT);
ctx.save();
ctx.fillStyle = "#000"
ball.draw();
player.draw();
ai.draw();
ctx.restore();
}