计算 window 调整大小时的圆圈大小

Calculating size of circles on window resize

在您可以 运行 下面的演示中,我生成了具有随机位置和大小的圆。

我将页面设置为在您调整 window 大小时重新加载,但这不是我想要的。 我想在 window 调整大小时重新计算圆圈的大小和位置,而不重新加载页面

我尝试了很多东西,但就是无法正常工作。任何帮助将不胜感激。


// Draw circles

const list = (length, callback) =>
  Array.from(new Array(length), (hole, index) => callback(index))

const random = (min, max) => Math.random() * (max - min) + min

const viewportWidth = Math.max(
  document.documentElement.clientWidth,
  window.innerWidth || 0
)

const viewportHeight = Math.max(
  document.documentElement.clientHeight,
  window.innerHeight || 0
)

const elements = list(48, () => {
  const circle = document.createElement("span")
  const minSize = Math.round((viewportWidth + viewportHeight) / 48)
  const maxSize = Math.round((viewportWidth + viewportHeight) / 24)
  const size = random(minSize, maxSize)
  Object.assign(circle.style, {
    width: `${size}px`,
    height: `${size}px`,
    left: `${random(0, 100)}%`,
    top: `${random(0, 100)}%`
  })
  return circle
})

document.body.append(...elements)

// Reload page on window resize

window.addEventListener("resize", () => {
  window.location.reload(true)
})
body { overflow: hidden }

span {
  background: black;
  position: absolute;
  border-radius: 50%;
  opacity: .5
}

使用 vh 或 vw ov vmax 或 vmin 单位代替 px

这里有一些解释https://web-design-weekly.com/2014-11-18-viewport-units-vw-vh-vmin-vmax/

vw: 1/100th viewport width

vh: 1/100th viewport height

vmin: 1/100th of the smallest side

vmax: 1/100th of the largest side

// Draw circles

const list = (length, callback) =>
  Array.from(new Array(length), (hole, index) => callback(index))

const random = (min, max) => Math.random() * (max - min) + min

const viewportWidth = Math.max(
  document.documentElement.clientWidth,
  window.innerWidth || 0
)

const viewportHeight = Math.max(
  document.documentElement.clientHeight,
  window.innerHeight || 0
)

const elements = list(48, () => {
  const circle = document.createElement("span")
  const minSize = Math.round((viewportWidth + viewportHeight) / 150) // tune this to your needs
  const maxSize = Math.round((viewportWidth + viewportHeight) / 80)// tune this to your needs
  const size = random(minSize, maxSize)
  Object.assign(circle.style, {
    width: `${size}vmin`,// vmin used instead px , but vh,vw aand vmax is also avalaible
    height: `${size}vmin`,// vmin used instead px , but vh,vw aand vmax is also avalaible
    left: `${random(0, 100)}%`,
    top: `${random(0, 100)}%`
  })
  return circle
})

document.body.append(...elements)
body { overflow: hidden }

span {
  background: black;
  position: absolute;
  border-radius: 50%;
  opacity: .5
}