简体   繁体   中英

how do I create an alternating stripe pattern with different stripe widths in javascript

I am trying to create a stripe pattern in javascript (p5.js), where the odd stripes are one width and the even are another.

If they were the same width, my code to create the pattern would be as follows:

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
  );
}

but if I were to introduce a barSize1 and barSize2 to create an alternating pattern of bars of different heights (say 2px and 8px), I can't figure out the equation that, in a loop, places the bars at the proper position.

How do I do this?

I had to write the code a bit differently because I've never used p5 and I had to follow the tutorial, but the important bit is the loop. Basically, add the bar height to a total each time and draw the next bar at the total height of the previous bars. Then stop drawing bars when the total height is higher than the window.

 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>

I adjusted the answer above so it fills up the entire screen on any screen incase you wanted to know how to do that:)

You can preview the sketch here: 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++;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM