如何在 p5.js 中获得未失真的 2D Perlin 噪声作为图像?
How can I get undistorted 2D Perlin noise as an image in p5.js?
我正在尝试在 p5.js 中绘制 Perlin 噪声图像。我遵循了 Daniel Shiffman 的教程,他给出了一个关于如何设置 2D Perlin 噪声的示例 here (for convenience I have loaded this into this JSFiddle sketch)。
现在我不需要整个 canvas 充满柏林噪声,但我只需要一个(较小的)柏林噪声图像,我可以像 canvas 中的图像文件一样使用它.因此,在设置函数中,我使用 createImage()
然后使用完全相同的算法将 Perlin 噪声加载到图像中。然而,当我现在显示这个时,噪声看起来完全失真了。
这是我的代码:
// noise code originally by
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/ikwNrFvnL3g
var inc = 0.01;
var noiseImg;
function setup() {
createCanvas(640, 360);
pixelDensity(1);
background("red");
var yoff = 0;
noiseImg = createImage(200, 200);
noiseImg.loadPixels();
for (var y = 0; y < height; y++) {
var xoff = 0;
for (var x = 0; x < width; x++) {
var index = (x + y * width) * 4;
var r = noise(xoff, yoff) * 255;
noiseImg.pixels[index + 0] = r;
noiseImg.pixels[index + 1] = r;
noiseImg.pixels[index + 2] = r;
noiseImg.pixels[index + 3] = 255;
xoff += inc;
}
yoff += inc;
}
noiseImg.updatePixels();
}
function draw() {
image(noiseImg, 0, 0);
}
有谁知道,为什么噪声算法没有改变但它会失真,我能做些什么?
谢谢!
width
和 height
变量适用于整个校园,在您的情况下分别为 640
和 360
。您使用这些变量遍历 space 中的每个像素,但随后您设置的图像像素阵列只有 200
乘以 200
像素。 (或者在你的 JSFiddle 中,300
by 300
pixels.)
这就是导致失真的原因:您在 200x200
图像上绘制 640x360
柏林噪声图。这会导致一些未定义的行为,表现为您所看到的失真。
要解决此问题,只需遍历图像的边界,而不是草图本身。
我正在尝试在 p5.js 中绘制 Perlin 噪声图像。我遵循了 Daniel Shiffman 的教程,他给出了一个关于如何设置 2D Perlin 噪声的示例 here (for convenience I have loaded this into this JSFiddle sketch)。
现在我不需要整个 canvas 充满柏林噪声,但我只需要一个(较小的)柏林噪声图像,我可以像 canvas 中的图像文件一样使用它.因此,在设置函数中,我使用 createImage()
然后使用完全相同的算法将 Perlin 噪声加载到图像中。然而,当我现在显示这个时,噪声看起来完全失真了。
这是我的代码:
// noise code originally by
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/ikwNrFvnL3g
var inc = 0.01;
var noiseImg;
function setup() {
createCanvas(640, 360);
pixelDensity(1);
background("red");
var yoff = 0;
noiseImg = createImage(200, 200);
noiseImg.loadPixels();
for (var y = 0; y < height; y++) {
var xoff = 0;
for (var x = 0; x < width; x++) {
var index = (x + y * width) * 4;
var r = noise(xoff, yoff) * 255;
noiseImg.pixels[index + 0] = r;
noiseImg.pixels[index + 1] = r;
noiseImg.pixels[index + 2] = r;
noiseImg.pixels[index + 3] = 255;
xoff += inc;
}
yoff += inc;
}
noiseImg.updatePixels();
}
function draw() {
image(noiseImg, 0, 0);
}
有谁知道,为什么噪声算法没有改变但它会失真,我能做些什么?
谢谢!
width
和 height
变量适用于整个校园,在您的情况下分别为 640
和 360
。您使用这些变量遍历 space 中的每个像素,但随后您设置的图像像素阵列只有 200
乘以 200
像素。 (或者在你的 JSFiddle 中,300
by 300
pixels.)
这就是导致失真的原因:您在 200x200
图像上绘制 640x360
柏林噪声图。这会导致一些未定义的行为,表现为您所看到的失真。
要解决此问题,只需遍历图像的边界,而不是草图本身。