<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Set the initial position of the circle
let x = canvas.width / 2;
let y = canvas.height / 2;
// Set the amount of pixels to move the circle in each frame
let dx = 2;
let dy = -2;
// Define a function to draw the circle at a given position
function drawCircle() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, 30, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
// Define a function to update the position of the circle
function updateCirclePosition() {
x += dx;
y += dy;
// Reverse direction if the circle hits the canvas edge
if (x + dx > canvas.width - 30 || x + dx < 30) {
dx = -dx;
}
if (y + dy > canvas.height - 30 || y + dy < 30) {
dy = -dy;
}
}
// Define the main animation loop
function animate() {
requestAnimationFrame(animate);
updateCirclePosition();
drawCircle();
}
// Start the animation loop
animate();
</script>