Open In App

How to create Animation of Sine Wave Pattern using p5.js ?

In this article, we are going to see how to create a Sine Wave Pattern animation using p5.js

p5.js is a JavaScript library that helps in creating graphics that users can interact with and is easy to use and helps in visualizing different kinds of graphics and animations. This article will show you how to create a Sine Wave Pattern using p5.js.



Approach: This code uses the p5.js library to generate a visual representation of a sine wave. The wave is generated by calculating the height (y-value) of each point on the wave using the sine function with a changing angle (theta). The resulting “y-values” are stored in an array, and then the wave is rendered by drawing a series of ellipses at each point on the wave.

 



Variables Used:

Functions used:

Example: In this example, we are going to create a Sine Wave Pattern animation, using p5.js.




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Animation of Sine Wave</title>
    <script src=
    </script>   
      
</head>
  
<body>
    <h2 style="color:green;">GeeksforGeeks</h2>
  
    <script>
        let xspacing = 8;    
        let w;              
        let theta = 0.0;     
        let amplitude = 75.0; 
        let period = 500.0;   
        let dx;             
        let yvalues;  
  
        function setup() {
            createCanvas(710, 400);
            w = width + 16;
            dx = (TWO_PI / period) * xspacing;
            yvalues = new Array(floor(w / xspacing));
        }
  
        function draw() {
            background(0);
            calcWave();
            renderWave();
        }
  
        function calcWave() {
            theta += 0.02;
  
            let x = theta;
            for (let i = 0; i < yvalues.length; i++) {
                yvalues[i] = sin(x) * amplitude;
                x += dx;
            }
        }
  
        function renderWave() {
            noStroke();
            fill(255, 50, 50);
            for (let x = 0; x < yvalues.length; x++) {
                ellipse(x * xspacing, height 
                        / 2 + yvalues[x], 16, 16);
            }
        }
    </script>
</body>
</html>

Output:

 

 


Article Tags :