【问题标题】:how do I create an alternating stripe pattern with different stripe widths in javascript如何在javascript中创建具有不同条纹宽度的交替条纹图案
【发布时间】:2021-01-02 00:28:52
【问题描述】:

我正在尝试在 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
  );
}

但如果我要引入 barSize1barSize2 来创建不同高度(比如 2px 和 8px)的条的交替模式,我无法弄清楚在循环中放置酒吧在适当的位置。

我该怎么做?

【问题讨论】:

    标签: javascript loops p5.js modulo


    【解决方案1】:

    我不得不编写代码有点不同,因为我从未使用过 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++;
      }
    }
    &lt;script src="https://cdn.jsdelivr.net/npm/p5@1.2.0/lib/p5.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:

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

      您可以在此处预览草图: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++;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-04
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多