I have been stuck this problem for few days. Couldn’t figure it out how create small increment in random number.
This is my code:
var jitter;
function setup() {
createCanvas(400, 400);
background(220);
strokeWeight(2);
noFill();
}
function draw() {
beginShape()
for (var i = 0; i < 300; i += 10) {
jitter = random(35, 45);
var y = 50 + i;
var x = jitter;
vertex(x, y);
}
endShape();
noLoop();
}
Basically what I want to do is to create a line that smooth in the top and curl / jitter in the bottom. My logic is to create vertex with random x. And make the x have small increment in the random number. But couldn’t find a way to do it
Here is one way to create a linear interpolation between the values.
var jitter = 0;
var jitterMax = 80;
function setup() {
createCanvas(400, 400);
background(220);
strokeWeight(2);
noFill();
}
function draw() {
// Translate makes it simpler to draw from on point
// p5js.org/reference/#/p5/translate
translate(35,45);
beginShape();
for (var i = 0; i < 300; i += 10) {
// The map function is an easy way to interpolate values
// p5js.org/reference/#/p5/map
jitter = map(i, 0, 300, 0, jitterMax);
var y = 50 + i;
var x = random(-jitter, jitter);
vertex(x, y);
}
endShape();
noLoop();
}
If you want to increment the values in a smoother way, have a look at logistic functions. I’m not an expert on this matter but tweeked the function a bit for this example.
var jitter = 0;
var jitterMax = 80;
var steps = 40;
function setup() {
createCanvas(400, 400);
background(220);
strokeWeight(2);
noFill();
}
function draw() {
translate(200, 50);
beginShape();
for (var i = 0; i < steps; i++) {
// This probalby needs improvement :)
var m = logistic(i/steps);
jitter = random(-jitterMax * m, jitterMax * m);
var y = map(i, 0, steps, 0, 300);
var x = random(-jitter, jitter);
vertex(x, y);
}
endShape();
noLoop();
}
function logistic(x) {
// Input for improvement here much appreciated
return (1 / (1 + Math.exp(-2 * (x - 0))) - 0.5) * 2;
}
logistic (or sigmoid) its a mathematical function often referred to as S-Curve.
You can write this principle as a javascript-function and use it.
Map() is sort of the same but you don’t have to write it yourself because it is already part of the P5JS library.