Browse Source

fix(component): balance word cloud layout and center it

main
Mohan 1 month ago
parent
commit
b6f514a4db
  1. 16
      src/components/TagCloud.vue

16
src/components/TagCloud.vue

@ -56,6 +56,7 @@ function buildLayout() {
const placed: { x: number; y: number; w: number; h: number }[] = [] const placed: { x: number; y: number; w: number; h: number }[] = []
let maxX = 0 let maxX = 0
let maxY = 0 let maxY = 0
let minX = Number.POSITIVE_INFINITY
const collides = (x: number, y: number, w: number, h: number): boolean => { const collides = (x: number, y: number, w: number, h: number): boolean => {
if (x < 2 || x + w > WIDTH - 2 || y < 2) return true if (x < 2 || x + w > WIDTH - 2 || y < 2) return true
@ -68,9 +69,9 @@ function buildLayout() {
let x = cx - w / 2 let x = cx - w / 2
let y = cy - h / 2 let y = cy - h / 2
if (!collides(x, y, w, h)) return [x, y] if (!collides(x, y, w, h)) return [x, y]
for (let t = 1; t < 900; t++) {
const angle = 0.75 * t
const rad = 3.4 * t
for (let t = 1; t < 1200; t++) {
const angle = 0.45 * t
const rad = 2.2 * t
x = cx + rad * Math.cos(angle) - w / 2 x = cx + rad * Math.cos(angle) - w / 2
y = cy + rad * Math.sin(angle) - h / 2 y = cy + rad * Math.sin(angle) - h / 2
if (!collides(x, y, w, h)) return [x, y] if (!collides(x, y, w, h)) return [x, y]
@ -92,10 +93,17 @@ function buildLayout() {
placed.push({ x, y, w, h }) placed.push({ x, y, w, h })
maxX = Math.max(maxX, x + w) maxX = Math.max(maxX, x + w)
maxY = Math.max(maxY, y + h) maxY = Math.max(maxY, y + h)
minX = Math.min(minX, x)
result.push({ tag, x, y, fontSize: fs, top: idx === 0 }) result.push({ tag, x, y, fontSize: fs, top: idx === 0 })
}) })
const spanX = maxX - minX
const vbW = Math.max(WIDTH, Math.ceil(spanX) + 8)
const shiftX = Math.max(2, (vbW - spanX) / 2) - minX
result.forEach((r) => {
r.x += shiftX
})
placedTags.value = result placedTags.value = result
viewBox.value = `0 0 ${Math.ceil(maxX) + 4} ${Math.ceil(maxY) + 4}`
viewBox.value = `0 0 ${vbW} ${Math.ceil(maxY) + 6}`
} }
function goToTag(tag: Tag) { function goToTag(tag: Tag) {

Loading…
Cancel
Save