月曜日, 4月 28, 2025

Let's start JavaScript 64 
HTML上で集中線を描画

HTML上で集中線をランダム描画します。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
<title>ランダム集中線</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 80vh;
background: #000;
}
canvas {
background: #000000;
            border: 1px solid #808080;
}
button {
margin-top: 10px;
padding: 3px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
    <h2><font color=
        "#ffffff">Random Concentration Line</font></h2>
<canvas id="speedLinesCanvas"></canvas>
<button onclick="drawSpeedLines()">再描画</button>

<script>
function drawSpeedLines() {
const canvas =
                document.getElementById("speedLinesCanvas");
const ctx = canvas.getContext("2d");

// キャンバスサイズを設定
canvas.width = 500;
canvas.height = 500;

// 中心座標
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;

// 設定値
const lineCount = 100; // 線の本数
const minLength = 50; // 最短の線の長さ
const maxLength = 200; // 最長の線の長さ
const lineWidth = 2; // 線の太さ
const lineColor = "yellow"; // 線の色(黒)

// 背景クリア
ctx.clearRect(0, 0, canvas.width, canvas.height);

// 線の描画
ctx.strokeStyle = lineColor;
ctx.lineWidth = lineWidth;

for (let i = 0; i < lineCount; i++) {
const angle = Math.random() * Math.PI * 2;
                    // 0〜360°のランダム角度
const length = minLength + Math.random() *
                    (maxLength - minLength); // ランダムな長さ

const endX = centerX + Math.cos(angle) * length;
const endY = centerY + Math.sin(angle) * length;

ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(endX, endY);
ctx.stroke();
}
}

// 初回描画
drawSpeedLines();
</script>

</body>
</html>

実行直後の状態です。

[再描画]でランダム描画を繰り返します。