我正在尝试使用HTML5 canvas元素制作破砖游戏。我已经完成了对大多数变量和函数的定义,因此我开始调用drawBall();。和drawPaddle();功能在主游戏循环中起作用,但是画布上没有任何显示。我已经尝试修复此问题已有一段时间了。任何有关如何解决此问题的建议将不胜感激。
这是我的代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var paddle = {
height: 15,
width: 100,
x: canvas.width / 2 - paddle.width / 2,
y: canvas.height - paddle.height
}; // defines the variables for the paddle.
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
} // when the right/left arrow key is pressed down, right/leftPressed = true.
function keyUpHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
} // when the left/right key is not being pressed anymore, right/leftPressed = false.
var bricks = {
brick1: true,
brick2: true,
brick3: true,
brick4: true,
brick5: true,
brick6: true,
brick7: true,
brick8: true,
brick9: true,
brick10: true
}; // to be put in the "active" parameter of the drawBricks function
var brickHeight = 15;
var brickWidth = 50;
var x = 200;
var y = 200;
var dx = 5;
var dy = -5;
var ballRadius = 10;
var rightPressed = false;
var leftPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#00F";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddle.x, paddle.y, paddle.width, paddle.height);
ctx.fillStyle = "0F0";
ctx.fill();
ctx.closePath();
}
function drawBricks(brickX, brickY, active) { // function for drawing, and the hit detection of the bricks.
if (active === true) {
ctx.startPath();
ctx.fillStyle = "#F00";
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fill();
ctx.closePath();
} // draws the bricks, if they are active.
if (
active === true &&
x >= brickX &&
x <= brickX + brickWidth &&
y <= brickY + brickHeight &&
y >= brickY
) {
active = false;
} // de-activates the bricks if the balls x and y are inside the brick.
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
} // if the ball hits either of the side walls, it goes the other way
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
} // if teh ball hits either the top wall or the bottom wall it goes the other way.
if (rightPressed) {
paddleX += 10;
} else if (leftPressed) {
paddleX -= 10;
} // changes the x position of the paddle based on which key is being pressed.
ctx.fillRect(200, 200, 200, 200);
x += dx;
y += dy;
} // main loop
setInterval(draw, 10);