Search code examples
javascriptp5.jsperlin-noise

How can I get undistorted 2D Perlin noise as an image in p5.js?


I'm trying to draw a Perlin noise image in p5.js. I followed Daniel Shiffman's tutorials and he gives an example about how to set up 2D Perlin noise here (for convenience I have loaded this into this JSFiddle sketch).

Now I don't need the entire canvas filled with Perlin noise, but I just need a (smaller) image of perlin noise that I can use like an image file in the canvas. So, in the setup function I used createImage() and then the exact same algorithm to load the Perlin noise into the image. However, when I display this now, the noise looks totally distorted.

Here is my code:

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

JSFiddle

Does anyone know, why it is distorted although the noise algorithm hasn't changed and what I can do about it?

Thanks!


Solution

  • The width and height variables are for the overall campus, in your case 640 and 360 respectively. You use these variables to loop over every pixel in that space, but then you're setting the pixel array of an image that's only 200 by 200 pixels. (Or in your JSFiddle, 300 by 300 pixels.)

    That's what's causing the distortion: you're drawing a 640x360 drawing of Perlin noise to a 200x200 image. This is resulting in some undefined behavior, which manifests as the distortion you're seeing.

    To fix the problem, just loop over the bounds of the image, not the sketch itself.