<div class="container">
<canvas id="ball"></canvas>
</div>
.container {
max-width: 680px;
}
canvas {
border: 4px solid rgba(0, 0, 0, .2);
}
// Get the canvas element and context
let canvas = document.querySelector("#ball");
let ctx = canvas.getContext("2d");
// Set the canvas width and height
canvas.width = 600;
canvas.height = 400;
// Set the initial x and y positions
let x = 300;
let y = 200;
// Set the velocity of the ball
let vx = 5;
let vy = 5;
// Set the radius of the ball
let radius = 50;
// Draw the ball
function drawBall() {
// Create a radial gradient
var gradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, "lightblue");
gradient.addColorStop(0.3, "cornflowerblue");
gradient.addColorStop(1, "midnightblue");
// Draw the ball
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
}
// Update the ball's position
function updateBall() {
// Update the x and y positions
x += vx;
y += vy;
// Check if the ball hits the left or right walls
if (x + radius > canvas.width || x - radius < 0) {
vx = -vx;
}
// Check if the ball hits the top or bottom walls
if (y + radius > canvas.height || y - radius < 0) {
vy = -vy;
}
}
// Main game loop
function gameLoop() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the ball
drawBall();
// Update the ball's position
updateBall();
// Call the game loop again
requestAnimationFrame(gameLoop);
}
// Call the game loop to start the animation
gameLoop();
This Pen doesn't use any external JavaScript resources.