1

I'm working on a music visualization and draw a curveVertex based on the songs amplitude. Therefore I'm using the p5.js sound library.

When the vertex hits the right end of the canvas, I want to force a line break but keep the lines above as single shapes. My current version only moves the whole vertex shape in the next line. Where is my thinking error?

const lineHeight = 30;
const paddingTop = lineHeight;
let currentLine = 1;

function draw() {
    background(0);
    amplitudeHistory.push(amplitude.getLevel());
    stroke(255);
    noFill();
    beginShape();

    for(let i = 0; i < amplitudeHistory.length; i++) {
        let y = map(amplitudeHistory[i], 0, 1, lineHeight + (paddingTop * currentLine) , lineHeight * (-1) + (paddingTop * currentLine));
        curveVertex(i, y);
    }
    endShape();

    if(amplitudeHistory.length > width * currentLine) {
        currentLine++;
    }
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
iamrobin.
  • 1,554
  • 3
  • 19
  • 31

1 Answers1

1

You need to draw 1 shape for each line. The number of lines which have to be drawn is calculated by

noOfLines = amplitudeHistory.length / width + 1;

Create a loop and run currentLine from 0 to < noOfLines. The data for a single line start at currentLine * width and end at (currentLine+1) * width respectively at amplitudeHistory.length for the last line:

let start = currentLine * width;
let end   = min(start + width, amplitudeHistory.length);

To draw the lines you need 2 nested loops:

function draw() {
    background(0);
    amplitudeHistory.push(amplitude.getLevel());
    stroke(255);
    noFill();

    let noOfLines = amplitudeHistory.length / width + 1;

    for (let currentLine = 0; currentLine < noOfLines; currentLine ++) {

        beginShape();

        let start = currentLine * width;
        let end   = min(start + width, amplitudeHistory.length);
        for (let i = start; i < end; i++) {
            let y = map(amplitudeHistory[i], 0, 1,
                        lineHeight + (paddingTop * currentLine),
                        lineHeight * (-1) + (paddingTop * currentLine));
            curveVertex(i-start, y);
        }

        endShape();
    }
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174