88 lines
1.9 KiB
JavaScript
88 lines
1.9 KiB
JavaScript
const canvas = document.getElementById("c");
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
const img = new Image();
|
|
img.src = "./images/1.jpg";
|
|
const thumbW = 100;
|
|
const thumbH = 100;
|
|
const gap = 10;
|
|
const columns = Math.floor(canvas.width / (thumbW + gap));
|
|
const count = 100;
|
|
let scrollTop = 0;
|
|
let selectedIndex = -1;
|
|
|
|
canvas.addEventListener("wheel", (e) => {
|
|
scrollTop += e.deltaY;
|
|
const rows = Math.ceil(count / columns);
|
|
const contentHeight = rows * (thumbW + gap);
|
|
|
|
let maxScroll = contentHeight - canvas.height;
|
|
if (maxScroll < 0) maxScroll = 0;
|
|
|
|
if (scrollTop < 0) scrollTop = 0;
|
|
if (scrollTop > maxScroll) scrollTop = maxScroll + 10;
|
|
|
|
render();
|
|
});
|
|
|
|
canvas.addEventListener("click", handleClick);
|
|
|
|
img.onload = () => {
|
|
render();
|
|
};
|
|
|
|
function getMousePos(e) {
|
|
const rect = canvas.getBoundingClientRect();
|
|
return {
|
|
x: e.clientX - rect.left,
|
|
y: e.clientY - rect.top,
|
|
};
|
|
}
|
|
|
|
function handleClick(e) {
|
|
const pos = getMousePos(e);
|
|
const mouseX = pos.x;
|
|
const mouseY = pos.y;
|
|
|
|
for (let i = 0; i < count; i++) {
|
|
const row = Math.floor(i / columns);
|
|
const col = i % columns;
|
|
|
|
const x = col * (thumbW + gap);
|
|
const y = row * (thumbH + gap) - scrollTop;
|
|
|
|
if (
|
|
mouseX >= x &&
|
|
mouseX <= x + thumbW &&
|
|
mouseY >= y &&
|
|
mouseY <= y + thumbH
|
|
) {
|
|
selectedIndex = i;
|
|
render();
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
function render() {
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
|
|
for (let i = 0; i < count; i++) {
|
|
const totalWidth = columns * (thumbW + gap) - gap;
|
|
const startX = (canvas.width - totalWidth) / 2;
|
|
const row = Math.floor(i / columns);
|
|
const col = i % columns;
|
|
|
|
const x = startX + col * (thumbW + gap);
|
|
const y = row * (thumbH + gap) - scrollTop;
|
|
|
|
ctx.drawImage(img, x, y + 10, thumbW, thumbH);
|
|
|
|
if (i === selectedIndex) {
|
|
ctx.strokeStyle = "red";
|
|
ctx.lineWidth = 4;
|
|
ctx.strokeRect(x, y + 10, thumbW, thumbH);
|
|
}
|
|
}
|
|
}
|