diff --git a/images/1.jpg b/images/1.jpg new file mode 100644 index 0000000..729e13b Binary files /dev/null and b/images/1.jpg differ diff --git a/images/2.jpg b/images/2.jpg new file mode 100644 index 0000000..fb19eaa Binary files /dev/null and b/images/2.jpg differ diff --git a/main.js b/main.js index ff5b6bb..c1cb48e 100644 --- a/main.js +++ b/main.js @@ -1,31 +1,87 @@ -console.log("load main.js success!"); const canvas = document.getElementById("c"); const ctx = canvas.getContext("2d"); -function render() { - ctx.clearRect(0, 0, canvas.width, canvas.height); +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; - ctx.fillStyle = "#eee"; - ctx.fillRect(0, 0, canvas.width, canvas.height); +canvas.addEventListener("wheel", (e) => { + scrollTop += e.deltaY; + const rows = Math.ceil(count / columns); + const contentHeight = rows * (thumbW + gap); - ctx.beginPath(); - ctx.moveTo(20, 20); - ctx.lineTo(200, 50); - ctx.strokeStyle = 'blue'; - ctx.lineWidth = 4; - ctx.stroke(); + let maxScroll = contentHeight - canvas.height; + if (maxScroll < 0) maxScroll = 0; - ctx.font = "20px Arial"; - ctx.fillStyle = "black"; - ctx.fillText("Canvas", 20, 100); + if (scrollTop < 0) scrollTop = 0; + if (scrollTop > maxScroll) scrollTop = maxScroll + 10; - requestAnimationFrame(render); + 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, + }; } -render(); +function handleClick(e) { + const pos = getMousePos(e); + const mouseX = pos.x; + const mouseY = pos.y; -canvas.addEventListener("click", (e) => { - const rect = canvas.getBoundingClientRect(); - const x = e.clientX - rect.left; - const y = e.clientY - rect.top; -}); + 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); + } + } +}