Converting from Processing to p5.js

Hi! I have a small little noise graphing code I would love to port to p5.js and have a hard time finding out what needs to change so this code (which works in processing) works in p5.js

float inc = 0.05;
float start = 0;

void setup(){
  size(600,400);

}

void draw() {
  background(0);
  stroke(255);
  noFill();
  beginShape();
  float xoff = start;
  for (float x = 0; x < width; x +=3) {
  stroke(255);
  strokeWeight(2);


float y = map(noise(xoff),0,1,150,250);
  vertex(x,y);
  xoff += inc;
  noiseDetail(10,0.5);  
}
   
endShape();
start += inc;
}

If anyone can help me I would be super happy.
Thank you!
Tilman

What have you tried in p5.js?

yes I have I get syntax error:

SyntaxError: Unexpected identifier
at /sketch.js:1:7

What is the code that produces that error?

Hi @Tilman ,

When copied and pasted into the online p5.js editor, the Java code that you posted produces this error message, which is the same as yours:

SyntaxError: Unexpected identifier
    at /sketch.js:1:7

Java code cannot be run in p5.js, which uses JavaScript.

Declaring a variable as float has no valid meaning in p5.js, because it is not valid JavaScript, and that explains the error message that you posted.

The translated code should begin as follows:

let inc = 0.05;
let start = 0;

function setup() {
  createCanvas(600,400);
}

Try translating the remainder of the code, and we can help if you have trouble.

1 Like

Thank you javager,
this was the right start. Had to translate a couple of other expressions too:
“Size” to “createCanvas”
“void” to “function”

But now it works as expected in p5.js
Working code:

let inc = 0.05;
let start = 0;

function setup(){
createCanvas(600,400);
}

function draw() {
  background(0);
  stroke(255);
  noFill();
  beginShape();
  let xoff = start;
  for (let x = 0; x < width; x +=3) {
  stroke(255);
  strokeWeight(2);


let y = map(noise(xoff),0,1,050,350);
  vertex(x,y);
  xoff += inc;
  noiseDetail(10,0.5);  
}
   
endShape();
start += inc;
}

Thanks again!

2 Likes

That’s much better JavaScript code now. :slight_smile:

It would be a good idea, however, to neaten up the indentation, so that the code becomes easier to read.