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)
I have two functions, one moving a ball randomly and one is supposed to be a paddle on the screen, now in order to move the ball I am calling drawBall with setInterval. The problem is my paddle does not show on screen and if I comment out the setinterval it shows on screen but my ball disappears.
Your drawBall method starts by clearing the canvas, so after you have drawn your paddle, the interval will clear it 10ms later. Fix this by removing the clearRect call from your drawBall function and re-drawing the paddle in every loop:
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPaddle();
drawBall();
}, 10)