I'm new to p5.js and I write this code to draw some random looping curve lines. But I don't know why my code doesn't return anything. Can somebody kindly points our my bugs? Thanks in advance!
var modifier1 = 300;
var modifier2 = 300;
var modifier3 = 2;
var addition = 90;
var count = 0;
function setup()
{
createCanvas(600, 600);
background(255);
}
function draw()
{
translate(width/2, height/2);
stroke(237, 34, 93);
beginShape();
while (count < 500)
{
var x = modifier1 * sin(radians(modifier3 * frameCount + addition));
var y = modifier2 * sin(radians(frameCount));
vertex(x,y);
count++;
}
endShape();
}
Your code doesn't draw anything, because you specify 500 vertices (vertex
) with the same coordinates. Note that x
and y
do not change because frameCount
does not change while the loop is running. Therefore, the shape only contains 500 identical points.
In the following frame, frameCount
has changed, but again you specify 500 vertices with the same coordinator. The coordinates are different from the coordinates in the previous frame, but the shape itself consists of 500 identical points.
If you use count
instead of frameCount
your shape will be drawn at once:
var modifier1 = 300;
var modifier2 = 300;
var modifier3 = 2;
var addition = 90;
var count = 0;
function setup()
{
createCanvas(600, 600);
background(255);
}
function draw()
{
translate(width/2, height/2);
stroke(237, 34, 93);
beginShape();
while (count < 500)
{
var x = modifier1 * sin(radians(modifier3 * count + addition));
var y = modifier2 * sin(radians(count));
vertex(x,y);
count++;
}
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
If you want to draw the shape "step by step" you need to add 1 segment from frameCount
to frameCount + 1
per frame:
var modifier1 = 300;
var modifier2 = 300;
var modifier3 = 2;
var addition = 90;
var count = 0;
function setup()
{
createCanvas(600, 600);
background(255);
}
function draw()
{
translate(width/2, height/2);
stroke(237, 34, 93);
beginShape();
var x1 = modifier1 * sin(radians(modifier3 * frameCount + addition));
var y1 = modifier2 * sin(radians(frameCount ));
vertex(x1, y1);
var x2 = modifier1 * sin(radians(modifier3 * (frameCount+1) + addition));
var y2 = modifier2 * sin(radians(frameCount+1));
vertex(x2, y2);
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>