为什么 setInterval 不让我的其他函数 运行?
Why is setInterval not letting my other functions run?
let paddleWidth = 100;
let paddleHeight = 25;
let paddlePositionX = 200
let paddlePositionY = 200
let ballPositionX = canvas.width /2; //ball position on x
let ballPositionY = canvas.height -150; //ball position on y
let dx = 5; //shift along x
let dy = 5; //shift along y
function drawPaddle(){
ctx.beginPath();
ctx.rect(paddlePositionX, paddlePositionY, paddlePositionY, paddleHeight);
ctx.rect(200, 200, 100,25)
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
drawPaddle()
function drawBall(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ballPositionX, ballPositionY, 15, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
ballPositionX += dx;
ballPositionY += dy;
if(ballPositionX >= canvas.width || ballPositionX + dx < 0){
dx = -dx;
}
if(ballPositionY + dy > canvas.height || ballPositionY + dy < 0) {
dy = -dy;
}
}
setInterval(drawBall, 10)
我有两个函数,一个随机移动一个球,一个应该是屏幕上的球拍,现在为了移动球我用 setInterval 调用 drawBall。问题是我的桨没有显示在屏幕上,如果我注释掉它在屏幕上显示的设置间隔,但我的球消失了。
您的 drawBall
方法从清除 canvas 开始,因此在您绘制桨后,间隔将在 10 毫秒后清除它。通过从 drawBall
函数中删除 clearRect
调用和每个循环中的 re-drawing 桨来解决此问题:
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPaddle();
drawBall();
}, 10)
let paddleWidth = 100;
let paddleHeight = 25;
let paddlePositionX = 200
let paddlePositionY = 200
let ballPositionX = canvas.width /2; //ball position on x
let ballPositionY = canvas.height -150; //ball position on y
let dx = 5; //shift along x
let dy = 5; //shift along y
function drawPaddle(){
ctx.beginPath();
ctx.rect(paddlePositionX, paddlePositionY, paddlePositionY, paddleHeight);
ctx.rect(200, 200, 100,25)
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
drawPaddle()
function drawBall(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ballPositionX, ballPositionY, 15, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
ballPositionX += dx;
ballPositionY += dy;
if(ballPositionX >= canvas.width || ballPositionX + dx < 0){
dx = -dx;
}
if(ballPositionY + dy > canvas.height || ballPositionY + dy < 0) {
dy = -dy;
}
}
setInterval(drawBall, 10)
我有两个函数,一个随机移动一个球,一个应该是屏幕上的球拍,现在为了移动球我用 setInterval 调用 drawBall。问题是我的桨没有显示在屏幕上,如果我注释掉它在屏幕上显示的设置间隔,但我的球消失了。
您的 drawBall
方法从清除 canvas 开始,因此在您绘制桨后,间隔将在 10 毫秒后清除它。通过从 drawBall
函数中删除 clearRect
调用和每个循环中的 re-drawing 桨来解决此问题:
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPaddle();
drawBall();
}, 10)