export type ImageMapOverlayBox = { key: string style: { left: number top: number width: number height: number borderRadius?: string clipPath?: string } } const parseCoords = (raw: string | null): number[] => (raw ?? "") .split(",") .map((value) => Number(value.trim())) .filter((value) => Number.isFinite(value)) // coords는 의 원본(naturalWidth/Height) 기준이라, 미리보기에서 이미지가 // 리사이즈되어 렌더링된 크기에 맞춰 스케일 변환한 뒤 컨테이너 기준 좌표로 옮겨야 한다. export function computeImageMapOverlayBoxes(container: HTMLElement): ImageMapOverlayBox[] { const boxes: ImageMapOverlayBox[] = [] const containerRect = container.getBoundingClientRect() const images = container.querySelectorAll("img[usemap]") images.forEach((img, imageIndex) => { if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) return const mapName = img.getAttribute("usemap")?.replace(/^#/, "") if (!mapName) return const map = container.querySelector(`map[name="${CSS.escape(mapName)}"]`) if (!map) return const imgRect = img.getBoundingClientRect() if (imgRect.width === 0 || imgRect.height === 0) return const scaleX = imgRect.width / img.naturalWidth const scaleY = imgRect.height / img.naturalHeight const offsetX = imgRect.left - containerRect.left const offsetY = imgRect.top - containerRect.top map.querySelectorAll("area").forEach((area, areaIndex) => { const shape = (area.getAttribute("shape") || "rect").toLowerCase() const coords = parseCoords(area.getAttribute("coords")) const key = `${imageIndex}-${areaIndex}` if (shape === "rect" && coords.length >= 4) { const [x1, y1, x2, y2] = coords boxes.push({ key, style: { left: offsetX + Math.min(x1, x2) * scaleX, top: offsetY + Math.min(y1, y2) * scaleY, width: Math.abs(x2 - x1) * scaleX, height: Math.abs(y2 - y1) * scaleY, }, }) return } if (shape === "circle" && coords.length >= 3) { const [cx, cy, r] = coords boxes.push({ key, style: { left: offsetX + (cx - r) * scaleX, top: offsetY + (cy - r) * scaleY, width: r * 2 * scaleX, height: r * 2 * scaleY, borderRadius: "9999px", }, }) return } if (shape === "poly" && coords.length >= 6 && coords.length % 2 === 0) { const xs = coords.filter((_, i) => i % 2 === 0) const ys = coords.filter((_, i) => i % 2 === 1) const minX = Math.min(...xs) const maxX = Math.max(...xs) const minY = Math.min(...ys) const maxY = Math.max(...ys) const width = maxX - minX const height = maxY - minY if (width <= 0 || height <= 0) return const points: string[] = [] for (let i = 0; i < coords.length; i += 2) { const px = ((coords[i] - minX) / width) * 100 const py = ((coords[i + 1] - minY) / height) * 100 points.push(`${px}% ${py}%`) } boxes.push({ key, style: { left: offsetX + minX * scaleX, top: offsetY + minY * scaleY, width: width * scaleX, height: height * scaleY, clipPath: `polygon(${points.join(", ")})`, }, }) } // shape="default"(이미지 전체)는 별도 오버레이 없이 그대로 둔다. }) }) return boxes }