代码之家  ›  专栏  ›  技术社区  ›  mheavers

如何在javascript中创建具有不同条纹宽度的交替条纹图案

  •  0
  • mheavers  · 技术社区  · 4 年前

    我试图在javascript(p5.js)中创建一个条纹模式,其中奇数条纹是一个宽度,偶数条纹是另一个宽度。

    如果它们的宽度相同,我创建模式的代码如下:

    const barSize = 5; //each bar is 5 pixels tall
    let numBars = Math.ceil(windowHeight / barSize); //number of bars to draw
    
    for (let i = 0; i < numBars; i++) {
      if (i % 2 === 0) {
        sketch.fill(234, 62, 246); //pink
      } else {
        sketch.fill(0); //black
      }
      sketch.rect( //create a rectangle at x, y, with window width, and barsize height (5 pixels)
        windowWidth / 2 - windowHeight / 2,
        barSize * i,
        windowWidth,
        barSize
      );
    }
    

    但如果我介绍一个 barSize1 barSize2 为了创建不同高度(比如2px和8px)的条形图的交替模式,我无法找出在循环中将条形图放置在适当位置的方程式。

    我该怎么做?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Will    4 年前

    我不得不以不同的方式编写代码,因为我从未使用过p5,我必须遵循教程,但重要的是循环。基本上,每次将条形高度相加,然后在前一个条形的总高度处绘制下一个条形。然后,当总高度高于窗口时,停止绘制条形图。

    function setup() {
      createCanvas(400, 200);
    
      const windowWidth = 400;
      const windowHeight = 200;
    
      let totalHeight = 0;
      let i = 0;
      let barSize;
    
      while (totalHeight < windowHeight) {
        if (i % 2 === 0) {
          fill(234, 62, 246); //pink
          barSize = 2;
        } else {
          fill(0); //black
          barSize = 8;
        }
    
        rect(windowWidth / 2 - windowHeight / 2, totalHeight, windowWidth, barSize);
    
        totalHeight += barSize;
        i++;
      }
    }
    <script src="https://cdn.jsdelivr.net/npm/p5@1.2.0/lib/p5.js"></script>
        2
  •  1
  •   SoftEngStudent    4 年前

    我调整了上面的答案,这样它就会填满任何屏幕上的整个屏幕,以防你想知道如何做到这一点:)

    您可以在此处预览草图: https://www.openprocessing.org/sketch/1057170

    function setup() {
      createCanvas(windowWidth, windowWidth);
    
      let totalHeight = 0; // this is your y
        let x = 0;
      let i = 0;
      let barSize;
    
      while (totalHeight < windowHeight) {
        if (i % 2 === 0) {
          fill(234, 62, 246); //pink
          barSize = 2;
        } else {
          fill(0); //black
          barSize = 8;
        }
    
        rect(x , totalHeight, windowWidth, barSize);
    
        totalHeight += barSize;
        i++;
      }
    }