月曜日, 8月 18, 2025

Let's start JavaScript 80 
HTMLで配置画像をクリックでランダム分割

配置画像をクリック毎にランダム分割で再配置させます。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ランダム分割</title>
<style>
body {
margin: 0;
background: #111;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
position: relative;
display: inline-block;
}
img, canvas {
display: block;
width: 640px;
height: auto;
cursor: pointer;
}
canvas {
position: absolute;
top: 0;
left: 0;
display: none;
pointer-events: none; /* クリックはimgにのみ反応させる */
}
</style>
</head>
<body>

<div class="container">
<!-- 表示フォントを指定 -->
<img id="sourceImage" src="links/picture.jpg"
    alt="クリックして分割">
<canvas id="canvas"></canvas>
</div>

<script>
const img = document.getElementById('sourceImage');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 読み込み後、キャンバスサイズを画像に合わせる
img.onload = () => {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
};

// 画像クリック時、ランダム分割表示
img.addEventListener('click', () => {
const rows = Math.floor(Math.random() * 4) + 2; // 2~5行
const cols = Math.floor(Math.random() * 4) + 2; // 2~5列

const cellW = canvas.width / cols;
const cellH = canvas.height / rows;

ctx.clearRect(0, 0, canvas.width, canvas.height);

for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const sx = Math.random() * (img.naturalWidth - cellW);
const sy = Math.random() * (img.naturalHeight - cellH);
const dx = c * cellW;
const dy = r * cellH;

ctx.drawImage(
img,
sx, sy, cellW, cellH,
dx, dy, cellW, cellH
);
}
}

// canvas 表示
canvas.style.display = 'block';
});
</script>

</body>
</html>


実行直後の画面

画像をクリック1回目

画像をクリック2回目