Home > other >  How to animate in p5.js?
How to animate in p5.js?

Time:09-24

I am trying to animate the lines but I have no Idea how to proceed.The code I worte so far is this.

 function setup() {
  createCanvas(400, 400);
  textSize(8);
}
function temp(){
  strokeWeight(5);
  point(150,108);
  point(56,75);
  point(121,185);
  strokeWeight(1);
  line(150,108,56,75);
  line(56,75,121,185);
}
function draw() {
  clear();
  background(220);
  translate(35,60);
  temp();
}

What I desire is the line comes up one by one according to the sequence they are drawn and when they are drawn the screen clear and again one by one basically it should come in sequence. I am not aware of how to do this.

GIF ===>https://thumbs.gfycat.com/SnoopyWildDuckbillcat.webp

The output I get is this The output

CodePudding user response:

Create a list of points:

var pointList = [[150, 108], [56, 75], [121, 185]]

Set the frame rate with frameRate():

frameRate(5);

Draw the lines between a number of points in a loop. The number of points to be drawn depends on the frameCount. Use the modulo (%) operator to compute the number of points (The % operator computes the remainder of a division:

function temp(){
    var noOfPoints = frameCount % (pointList.length 1);
    strokeWeight(5);
    for (var i = 0; i < noOfPoints; i  ) {
        point(...pointList[i]);
    }
    strokeWeight(1);
    for (var i = 0; i < noOfPoints-1; i  ) {
        line(...pointList[i], ...pointList[i 1]);
    }
}

Example:

var pointList = []

function setup() {
    createCanvas(220, 220);
    frameRate(5);
    for (var i = 0; i <= 10; i  ) {
        var angle = TWO_PI * i / 10;
        var radius = i % 2 == 0 ? 100 : 50;
        pointList.push([radius * sin(angle), radius * -cos(angle)])
    }
}

function temp(){
    var noOfPoints = frameCount % (pointList.length 1);
    strokeWeight(5);
    for (var i = 0; i < noOfPoints; i  ) {
        point(...pointList[i]);
    }
    strokeWeight(1);
    for (var i = 0; i < noOfPoints-1; i  ) {
        line(...pointList[i], ...pointList[i 1]);
    }
}

function draw() {
    clear();
    background(220);
    translate(110, 110);
    temp();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

CodePudding user response:

create an array of objects that have coordinates and know how to be drawn. in the draw function you can then iterate through the array, modify the coordinates of each object according to your logic and call their draw method.

having the call to background in the draw function you can remove the clear call because the background will draw over the lines

  • Related