0

I'm using P5.js and the Perlin noise() function to try and draw a circle with Perlin noise generated x and y coordinates. I don't get any error messages but nothing is drawn on the canvas. What am I doing wrong?

let width;
let height;

function setup() {
    createCanvas(windowWidth, windowHeight);
    width = windowWidth;
    height = windowHeight;
}

var Circle = function () {
    this.x = width / 2;
    this.y = height / 2;
    this.tx = 0;
    this.ty = 0;
};

Circle.prototype.display = function () {
    stroke(0);
    ellipse(this.x, this.y, 200, 200);
};

Circle.prototype.walk = function () {
    this.x = map(noise(this.x), 0, 1, 0, width);
    this.y = map(noise(this.y), 0, 1, 0, height);
    this.tx += 0.01;
    this.ty += 0.01;
};

var c = new Circle();

function draw() {
    c.walk();
    c.display();
}
<html>

<head>
    <meta charset="UTF-8">
    <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

    <script language="javascript" type="text/javascript" src="sketch.js"></script>

    <style>
        body {
            padding: 0;
            margin: 0;
        }

    </style>
</head>

</html>
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107

1 Answers1

1

You should get into the habit of debugging your code to understand exactly what's going on. For example, I would add something like this to your walk() function:

console.log(this.x);

This will help you understand what's going on. You'll find out that this.x is always null. You can then trace back through the code to find out why.

Another thing that jumps out to me is that you shouldn't define your own width and height variables. Instead, use the width and height variables that P5.js provides for you.

Tracing through the code, you should also think about exactly when this line happens:

var c = new Circle();

This line of code is executed before the setup() function is called. My guess is you originally got an error saying width was undefined, which is why you added your own width variable. But that didn't really solve the problem, which is that all of this code is happening before the setup() function is being called.

To fix this, just move the initialization to be inside the setup() function:

var c;

function setup() {
    createCanvas(windowWidth, windowHeight);
      c = new Circle();
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • Thanks so much, that's exactly what happened before I defined my own width and height. This was very helpful, sorry if my question was so open-ended. – joaquinkai Jun 05 '18 at 02:44