How to make a circle to move randomly in a canvas?

by giovanny.lueilwitz , in category: Javascript , 3 months ago

How to make a circle to move randomly in a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 3 months ago

@giovanny.lueilwitz 

To make a circle move randomly in a canvas using JavaScript, you can follow these steps:

  1. Create an HTML file with a canvas element in it. Give the canvas an id attribute so you can reference it in your JavaScript code.
 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. Create a JavaScript file (e.g. script.js) and write the following code to draw a circle on the canvas and move it randomly:
 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();


  1. Save the HTML and JavaScript files in the same directory and open the HTML file in a web browser. You will see a blue circle moving randomly on the canvas.


You can adjust the circle's size, color, velocity, and canvas size in the code to customize the movement as desired.