Update bouncing ball

This commit is contained in:
LSvekis
2021-07-02 13:14:48 -04:00
committed by GitHub
parent b622b53932
commit dd66ed1848
+10 -10
View File
@@ -18,8 +18,8 @@ const ctx = canvas.getContext("2d");
const ballSize = 10; const ballSize = 10;
let x = canvas.width/2; let x = canvas.width/2;
let y = canvas.height/2; let y = canvas.height/2;
let dx = 1; let dirX = 1;
let dy = 1; let dirY = 1;
function drawBall() { function drawBall() {
ctx.beginPath(); ctx.beginPath();
ctx.arc(x, y, ballSize, 0, Math.PI*2); ctx.arc(x, y, ballSize, 0, Math.PI*2);
@@ -27,19 +27,19 @@ function drawBall() {
ctx.fill(); ctx.fill();
ctx.closePath(); ctx.closePath();
} }
function draw() { function move() {
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall(); drawBall();
if(x + dx > canvas.width-ballSize || x + dx < ballSize) { if(x > canvas.width-ballSize || x < ballSize) {
dx *= -1; dirX *= -1;
} }
if(y + dy > canvas.height-ballSize || y + dy < ballSize) { if(y > canvas.height-ballSize || y < ballSize) {
dy *= -1; dirY *= -1;
} }
x += dx; x += dirX;
y += dy; y += dirY;
} }
setInterval(draw, 10); setInterval(move, 10);
</script> </script>
</body> </body>