p5.j​​s顶点形状换行

时间:2019-09-14 12:44:03

标签: javascript processing p5.js

我正在进行音乐可视化,并根据歌曲的振幅绘制一个curveVertex。因此,我正在使用p5.js声音库。

当顶点碰到画布的右端时,我想强制换行,但将上面的线保持为单个形状。我当前的版本仅在下一行移动整个顶点形状。我的思维错误在哪里?

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

1 个答案:

答案 0 :(得分:1)

您需要为每条线绘制1个形状。

noOfLines = amplitudeHistory.length / width + 1;

创建一个循环,将currentLine从0运行到< noOfLines。一行的数据从currentLine * width开始,到(currentLine+1) * widthamplitudeHistory.length的最后一行分别结束:

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

要绘制线条,您需要2个嵌套循环:

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