In this tutorial, we will learn how to move a ball inside a rectangle shape using JavaScript. This will involve creating a canvas element on which we will draw the rectangle and the ball. We will then use JavaScript to animate the movement of the ball inside the rectangle.
Step 1: Setting up the HTML
First, create an HTML file and add a canvas element to it. This canvas element will serve as the drawing board for our rectangle and ball.
<!DOCTYPE html>
<html>
<head>
<title>Move Ball in Rectangle Shape</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
Step 2: Drawing the Rectangle and Ball
Next, create a JavaScript file (script.js) and start by getting a reference to the canvas element and its context. Then, use the context to draw a rectangle and a ball on the canvas.
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Draw the rectangle
ctx.rect(50, 50, 500, 300);
ctx.fillStyle = 'lightblue';
ctx.fill();
// Draw the ball
var ballX = 100;
var ballY = 100;
var ballRadius = 20;
ctx.beginPath();
ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
Step 3: Animating the Ball
Now, we will add an animation loop that will continuously update the position of the ball and redraw it on the canvas. We will also add logic to ensure that the ball stays within the bounds of the rectangle.
function animate() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the rectangle
ctx.rect(50, 50, 500, 300);
ctx.fillStyle = 'lightblue';
ctx.fill();
// Update the ball position
ballX += 1;
if (ballX + ballRadius > 550 || ballX - ballRadius < 50) {
ballX -= 2;
}
// Draw the ball
ctx.beginPath();
ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
// Request the next animation frame
requestAnimationFrame(animate);
}
animate();
Step 4: Running the Animation
Save all your files and open the HTML file in a web browser. You should see a rectangle with a ball moving inside it. The ball should bounce off the walls of the rectangle and stay within its bounds.
Congratulations! You have successfully implemented a simple animation using JavaScript to move a ball inside a rectangle. You can further enhance this animation by adding more balls, randomizing their starting positions, or changing their speed and direction based on user input.
Guru jee playlist seedhi karne ke liye program kaise likhen…
Nice