水曜日, 5月 07, 2025

Let's start JavaScript 66 
HTML上で指定画像を隙間を空けて分割

指定画像を指定数で分割し隙間を空けて表示します。画像は正方形であればサイズは強制的に400px四方になります。正方形でない場合は強制的にデフォルメされます。
以下の改良版です。



<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>画像分割ビューワー</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background: darkgray;
}

form {
margin-bottom: 20px;
}

.grid {
display: grid;
background: darkgray;
}

.cell {
/* ↓ 差し替えてください */
background-image: url("links/image.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
}
</style>
</head>
<body>
<h3>画像グリッド分割(ユーザー入力)</h3>
<form id="form">
行数: <input type="number" style="width:50px;"
id="rows" value="4" min="1" required>
列数: <input type="number" style="width:50px;"
id="cols" value="4" min="1" required>
隙間(px): <input type="number" style="width:50px;"
id="gap" value="4" min="0" required>&emsp;
<button type="submit" style="width:50px;">表示</button>
</form>

<div class="grid" id="grid"></div>

<script>
const form = document.getElementById("form");
const grid = document.getElementById("grid");

const imageWidth = 400;
const imageHeight = 400;
const imageURL = "links/image.jpg"; // ← 任意の画像に変更可能

form.addEventListener("submit", function (e) {
e.preventDefault();

// 入力値取得
const rows = parseInt(document.getElementById("rows").value);
const cols = parseInt(document.getElementById("cols").value);
const gap = parseInt(document.getElementById("gap").value);

// セルサイズ計算
const cellWidth = (imageWidth - gap * (cols - 1)) / cols;
const cellHeight = (imageHeight - gap * (rows - 1)) / rows;

// グリッド設定
grid.innerHTML = "";
grid.style.width = `${imageWidth}px`;
grid.style.height = `${imageHeight}px`;
grid.style.gridTemplateColumns =
`repeat(${cols}, ${cellWidth}px)`;
grid.style.gridTemplateRows =
`repeat(${rows}, ${cellHeight}px)`;
grid.style.gap = `${gap}px`;

// セル作成
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const cell = document.createElement("div");
cell.className = "cell";
cell.style.width = `${cellWidth}px`;
cell.style.height = `${cellHeight}px`;
cell.style.backgroundImage = `url('${imageURL}')`;
cell.style.backgroundSize =
`${imageWidth}px ${imageHeight}px`;
cell.style.backgroundPosition =
`-${col * (imageWidth / cols)}px
-${row * (imageHeight / rows)}px`;
grid.appendChild(cell);
}
}
});
</script>
</body>
</html>

元画像は800×800pxです。

実行したら[行数][列数][隙間]を入力して[表示]ボタンをクリックします。

上はデフォルト設定の結果。

値を変更して再度[表示]ボタンをクリック。