@giovanny.lueilwitz
To make a circle move randomly in a canvas using JavaScript, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Circle Movement</title> </head> <body> <canvas id="myCanvas" width="500" height="500"></canvas> <script src="script.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); let x = canvas.width / 2; let y = canvas.height / 2; let dx = Math.random() * 2 - 1; // Random velocity for x direction let dy = Math.random() * 2 - 1; // Random velocity for y direction function drawCircle() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas ctx.beginPath(); ctx.arc(x, y, 20, 0, Math.PI * 2); ctx.fillStyle = 'blue'; ctx.fill(); ctx.closePath(); x += dx; y += dy; if (x > canvas.width - 20 || x < 20) { dx = -dx; // Reverse x direction if circle hits canvas boundaries } if (y > canvas.height - 20 || y < 20) { dy = -dy; // Reverse y direction if circle hits canvas boundaries } requestAnimationFrame(drawCircle); // Repeat the drawing } drawCircle(); |
You can adjust the circle's size, color, velocity, and canvas size in the code to customize the movement as desired.