2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】振り子もどき

Last updated at Posted at 2024-07-31

furiko.gif

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>振り子もどき</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <canvas></canvas>

  <script src="main.js"></script>
</body>
</html>
main.js
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

canvas.width = 800;
canvas.height = 500;

const baseX = 400;
const baseY = 150;
const ballRadius = 20;
const g = 9.80665;

let t = 0;
const fps = 60;

setInterval(() => {
    context.clearRect(0, 0, canvas.width, canvas.height);

    const colors = ["purple", "blue", "green", "red", "orange"];

    for (let i = 4; i >= 0; i--) {
        for (let j = 4; j >=0; j--) {
            const l = 60 * (i + 1);
            const maxRadian = Math.PI / 8 * (j + 1);
            const angularFrequency = Math.sqrt(g / l);
            const radian = maxRadian * Math.cos(angularFrequency * t);

            const x = baseX + l * Math.sin(radian);
            const y = baseY + l * Math.cos(radian);
            drawPendulum(x, y, ballRadius, colors[i], (j + 1) / 5);
        }
    }

    t += 1 / fps * 10;
}, 1000 / fps);

function drawPendulum(x, y, r, color = "black", alpha = 1) {
    context.beginPath();
    context.globalAlpha = 0.2;
    context.moveTo(baseX, baseY);
    context.lineTo(x, y);
    context.stroke();
    context.beginPath();
    context.arc(x, y, r, 0, Math.PI * 2);
    context.fillStyle = color;
    context.globalAlpha = alpha;
    context.fill();
}

ちゃんとした振り子を作りたい場合は運動方程式がどーのこーの、微分積分がどーのこーのとしないといけない。

これは振り子っぽいやつを作っている。

参考にしたサイト

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?