尝试使用 p5.js 获得响应 window 和形状

Trying to get responsive window and shapes using p5.js

我正在完成 JavaScript 教程(使用 p5.js),并且有兴趣编写一个具有四个形状的响应式屏幕,这些形状在这样做时会按比例缩小并彼此相邻。

为 y 定义一个单独的变量是否足够,还是通过一组新的 x 和 y 变量重新定义所有形状会更好? Window height/width 似乎 应该是正确的代码。

我的代码:

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);
}

function draw() {
  background(200);
  noStroke();

  var labelw = window.innerWidth/8;
  var labelh = labelw/4;
  var sectionw = window.innerWidth;
  var sectionh = window.innerHeight;

  // Red
  if(window.innerWidth/2 < window.innerHeight){
    fill(200, 50, 50);
    rect(0, 0, sectionw/2, sectionw/4)
  }

  // Blue
  if(window.innerWidth/2 < window.innerHeight){
    fill(50, 50, 200);
    rect(sectionw/2, 0, sectionw/2, sectionw/4)
  }

  // Green
  if(window.innerWidth/2 < window.innerHeight){
    fill(130, 230, 130);
    rect(0, sectionh/2, sectionw/2, sectionw/4)
  }

  // Purple
  if(window.innerWidth/2 < window.innerHeight){
    fill(190, 100, 230);
    rect(sectionw/2, sectionh/2, sectionw/2, sectionw/4)
  }

  // label1
  fill(50)
  rect(0, 0, labelw, labelh)
  fill(255);
  textSize(labelw/10);
  text("Test Label\nTestIdeo, 19xx-20xx",0, 0, 200, 200);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
<html>
  <head></head>
  <body></body>
</html>

你需要做两件事:

首先,您需要检测屏幕何时调整大小,并在发生这种情况时调整 canvas 的大小。 windowResized()resizeCanvas() 函数可以派上用场。有关详细信息,请参阅 the reference

其次,您只需要使用 widthheight 变量来绘制形状。当您调整 canvas.

大小时,widthheight 变量会自动更新

把它们放在一起,看起来像这样:

function setup() {
    createCanvas(windowWidth, windowHeight);
} 

function draw() {
    fill(255, 0, 0);
    rect(0, 0, width/2, height/2);

    fill(0, 255, 0);
    rect(width/2, 0, width/2, height/2);

    fill(0, 0, 255);
    rect(0, height/2, width/2, height/2);

    fill(255, 255, 0);
    rect(width/2, height/2, width/2, height/2);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}