首页 > 解决方案 > 如何制作一个网格,使单元格在任何给定的纵横比下尽可能呈正方形?

问题描述

我正在绘制一个点网格,基本上是一个嵌套数组:

const colWidth = (p5.width / cols)
const colHeight = (p5.height / rows)


for (let x = 0; x < cols+1; x++) {
  for (let y = 0; y < rows+1; y++) {
    spots.push(Spot(p5, x * colWidth, y * colHeight))
  }

Spot 是一个接受 x 和 y 位置的对象。

问题是,根据窗口的大小和高度,点的网格会被拉伸或挤压,我想要的是,无论窗口有哪些尺寸,网格都尽可能保持“正方形”,我的意思是,由点组成的正方形形成正方形而不是矩形,不一定是 100% 正方形,只要给定窗口尺寸尽可能接近即可。

我试过,得到宽度和高度相对于彼此的比例,然后将该数字乘以细分数字,然后将列和行设置为结果,但这不起作用。它看起来仍然很紧张。

let windowWidthProportion = p5.width/p5.height
let windowHeightProportion = p5.height/p5.width 

cols = windowWidthProportion * subdivision
rows = windowHeightProportion * subdivision

知道如何让它工作吗?谢谢。

我的草图:

export default function Sketch(p5) {
  ...
  
  function Spot(p5, x, y) {
    ...
  }

  p5.setup = (canvasParentRef) => {
    canvas = p5.createCanvas(p5.windowWidth, p5.windowHeight /*, p5.WEBGL*/)
 
    let windowWidthProportion = p5.width/p5.height // 200   
    let windowHeightProportion = p5.height/p5.width // 100

    cols = windowWidthProportion * subdivision
    rows = windowHeightProportion * subdivision

    const colWidth = (p5.width / cols)
    const colHeight = (p5.height / rows)

    p5.background(0);
    for (let x = 0; x < cols+1; x++) {
      for (let y = 0; y < rows+1; y++) {
        spots.push(Spot(p5, x * colWidth, y * colHeight))
      }
    }
  }

  p5.draw = () => {
    ...
    spots.forEach((s, i) => {
      let { _x, _y, hovered } = s.values()
      s.randomWalk()
      s.display()
      if (i !== 0 && isOverGridPoint(p5.mouseX, p5.mouseY, _x, _y)) s.flash() 
      hovered && s.fade()
    })
  };
}

标签: p5.js

解决方案


推荐阅读