优化代码以生成静态

问题描述 投票:1回答:2

我正在学习p5.js并希望生成一个“静态/噪声纹理”,如下所示:

enter image description here

这是代码:

for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    noiseVal = random(0,1);
    stroke(255, noiseVal*255);
    point(x,y);
  }
}

这会产生预期的结果,但它显然非常慢,因为它必须迭代每个像素。这样做更有效的方法是什么?

optimization processing p5.js
2个回答
1
投票

您的代码实际上不是处理p5.js的最佳方式。

Take a look to the p5's pixels array.

当我运行以下代码时,使用像素数组的函数运行速度快100倍。

function setup() {
    createCanvas(50, 50);
    background(255);

    let start, time;

    start = performance.now();
    noise_1();
    time = performance.now() - start;
    print("noise_1 : " + time);

    start = performance.now();
    noise_2();
    time = performance.now() -start;
    print("noise_2 : " + time);

}

// Your code
function noise_1() {
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            noiseVal = random(0,1);
            stroke(noiseVal*255);
            point(x,y);
        }
    }
}

// same with pixels array
function noise_2() {
    loadPixels();
    for (let i=0; i < pixels.length; i+=4){
        noiseVal = random(0,    255);
        pixels[i] = pixels[i+1] = pixels[i+2] = noiseVal;
    }
    updatePixels();
}

输出:

noise_1 : 495.1
noise_2 : 5.92

1
投票

要生成单帧静态,您将不得不迭代每个像素。你可以使你的块大于一个像素,但这只会减少问题,而不是完全摆脱它。

相反,你可以通过预先计算一些静态图像(比如10个左右)来逃避。将它们保存为文件或屏幕外缓冲区(createGraphics()函数是您的朋友),然后绘制这些图像而不是每帧绘制每个像素。

© www.soinside.com 2019 - 2024. All rights reserved.