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?
Advertisement
Answer
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>