【问题标题】:How to resize a canvas properly in React using p5js?如何使用 p5js 在 React 中正确调整画布的大小?
【发布时间】:2022-11-09 19:55:13
【问题描述】:

我目前正在做一个项目,其中一部分是在调整画布大小(或调整窗口大小)后调整画布中模型的大小。我检查了resizeCanvas() 的文档并应用了它。

我首先通过将currentWidth/defaultWidth 分别除以用户设备的 currentWidth 和我们的默认/选定宽度来找到比率。

  findRatio(wd, hd, wc, hc) {
    const w = wc / wd;
    const h = hc / hd;
    return w < h ? w : h;
  }

在我的windowResized() 函数中,一旦在窗口调整大小时调整画布大小,我就会设置宽度/高度。

export const windowResized = (p5) => {
  if (p5) {
    initVariables.browserWidth = p5.windowWidth;
    initVariables.browserHeight = p5.windowHeight;
    p5.resizeCanvas(initVariables.browserWidth, initVariables.browserHeight);
    for (let m of initVariables.mM) {
      m.updateonResize();
    }
  }
};

这里 initVariables 只是一个带有一些变量的对象。

我的父类中还有updateonResize() 函数,一旦调整窗口大小就会触发。

 updateonResize() {
    this.r = this.findRatio(
      this.initVariables.width,
      this.initVariables.height,
      this.initVariables.browserWidth,
      this.initVariables.browserHeight
    );
    this.arr.push(this.r);

    if (this.arr[this.arr.length - 2] !== undefined) {
      if (this.r < this.arr[this.arr.length - 2]) {
        console.log("canvas getting larger, not sure if I need to divide or multiply here");
        this.min = this.min * this.r;
        this.max = this.max * this.r;
        this.measure = this.measure * this.r;
      } else {
        this.min = this.min * this.r;
        this.max = this.max * this.r;
        this.measure = this.measure * this.r;
      }
    }
  }

这里,minmaxmeasure 变量是用于检测对象部分的大小(即行长)的变量。如果画布越来越小,您需要乘法测量ratio 的值(其中比率通常小于 1)。

问题1:我在 Chrome 浏览器中从全屏模式进入窗口模式时遇到问题。它不会触发windowOnResize() 函数。进入窗口模式后是否可以自动触发此功能?

问题2:当您调整浏览器大小时,比率每帧都会发生变化,因此measure*ratio 的值变得太低(到 0)。有没有我可以应用的算法来稍微降低测量值,但不会大幅降低?

【问题讨论】:

    标签: javascript reactjs canvas p5.js


    【解决方案1】:

    我自己找到了解决方案。我已经使用 JavaScript 添加了调整大小事件侦听器,并用我自己的函数找到了比率,并用它调整了画布的大小。我已经添加了超时,而不是同时看到更改,但经过一些延迟。

    let timeOutFunctionId;
    
    window.addEventListener("resize", function () {
      if (!initVariables.subSet) {
        r = findRatio(
          initVariables.width,
          initVariables.height,
          initVariables.browserWidth,
          initVariables.browserHeight
        );
        clearTimeout(timeOutFunctionId);
        timeOutFunctionId = setTimeout(() => {
          if (p5) {
            if (true) {
              initVariables.browserWidth = p5.windowWidth - 310;
              initVariables.browserHeight = p5.windowHeight - 200;
            } else {
            }
            p5.resizeCanvas(
              initVariables.browserWidth,
              initVariables.browserHeight
            );
            //calling custom class 
          }
        }, 500);
      }
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 2017-01-26
      • 2020-09-30
      • 2021-03-16
      • 2020-04-26
      • 2011-01-11
      • 1970-01-01
      相关资源
      最近更新 更多