JSFiddle - React, Tailwind, and code Playground
by aaronamran
HTML
<!DOCTYPE html>
<html>
<head>
<title>Pendulum Visualization</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Define parameters
const arcWidth = 100; // Width of the pendulum's arc
const angleRange = Math.PI / 4; // Angle range for bob's motion (45 degrees)
const tMax = 50;
const numOsci = 2;
// Calculate the angular velocity in terms of θ and time (t)
const angularVelocity = 2 * Math.PI / (tMax * numOsci); // Adjust as needed
// Create an array to store the coordinates
const coordinates = [];
// Initialize variables
let angle = 0; // Start at the maximum angle
let direction = 1; // Direction of oscillation
// Generate the coordinates
for (let i = 0; i < canvas.width; i++) {
const x = canvas.width / 2 + arcWidth * Math.cos(angle);
const y = canvas.height / 2 + arcWidth * Math.sin(angle);
coordinates.push({
x,
y
});
// Update the angle for the next frame
angle += angularVelocity * direction;
// Change direction when the bob reaches the angle limit
if (angle > angleRange / 2 || angle < -angleRange / 2) {
direction *= -1;
}
}
// Draw the pendulum
function drawPendulum(frame) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the pendulum string (vertical line)
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
ctx.lineTo(coordinates[frame].x, coordinates[frame].y);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
// Draw the pendulum bob (circle)
ctx.beginPath();
ctx.arc(coordinates[frame].x, coordinates[frame].y, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
...