优化代码生成静态

Optimizing code to generate static

我正在学习 p5.js 并且想生成一个 "static/noise texture" 像这样:

这是代码:

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

这会产生预期的结果,但显然速度很慢,因为它必须遍历每个像素。执行此操作的更有效方法是什么?

要生成单帧静态图像,您将不得不遍历每个像素。你可以让你的块大于一个像素,但这只会减少问题,并不能完全消除它。

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

您的代码确实不是处理 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