我正在学习p5.js并希望生成一个"静态/噪音纹理"像这样:
这是代码:
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);
}
}
这会产生预期的结果,但它显然非常慢,因为它必须遍历每个像素。什么是更有效的方法呢?
答案 0 :(得分:1)
要生成单帧静态,您将不得不迭代每个像素。你可以让你的块大于一个像素,但这只会减少问题,而不是完全摆脱它。
相反,你可以通过预先计算一些静态图像(让我们说10个左右)来逃避。将它们保存为文件或屏幕外缓冲区(createGraphics()
函数是您的朋友),然后绘制这些图像而不是每帧绘制每个像素。
答案 1 :(得分: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