木曜日, 8月 28, 2025

Let's start JavaScript 81 
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 {
text-align: center;
font-family: Arial, sans-serif;
background-color: Black;
}
canvas {
border: 2px solid black;
margin-top: 10px;
background: white;
border: 1px solid white;
}
</style>
</head>
<body>

<h3>
    <font color="white">Random diagonal line drawing</font>
    </h3>
<label for="lineCount">線の本数:</label>
<input type="number" id="lineCount" value="10" min="1">
<button onclick="drawRandomLines()">描画</button>

<br>
<canvas id="canvas" width="500" height="500"></canvas>
<!-- canvas の width や height を変更すれば、
描画エリアを大きく or 小さくできます。 -->

<script>
function drawRandomLines() {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const numLines = parseInt(document.
                getElementById("lineCount").value, 10);

if (isNaN(numLines) || numLines < 1) {
alert("正しい本数を入力してください!");
return;
}

// キャンバスをクリア
// ctx.globalAlpha = 0.5; を追加すると、
            // 半透明の線を描画できます。
ctx.clearRect(0, 0, canvas.width, canvas.height);

for (let i = 0; i < numLines; i++) {
// ランダムな開始点と終了点
let x1 = randomRange(0, canvas.width);
let y1 = randomRange(0, canvas.height);
let x2 = randomRange(0, canvas.width);
let y2 = randomRange(0, canvas.height);

// ランダムな線の太さ
let lineWidth = randomRange(1, 15);
// randomRange(1, 15); の範囲を変更すると、
// 線の太さを太く or 細く 調整可能。

// ランダムなRGBカラー
let color = `rgb(${randomRange(0, 255)},
${randomRange(0, 255)}, ${randomRange(0, 255)})`;

// 線を描画
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = color;
ctx.stroke();
}
}

// min~maxの範囲でランダムな数を生成
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</body>
</html>

実行北後の画面です。数値(デフォルトは10)を入力して[描画]をクリックすれば・・・

枠内に表示されます。

100で実行した結果。