Open In App

Create an object that follows the mouse pointer using p5.js

In this article, we are going to create an object, that will follow the mouse pointer. As the mouse circle move, that entity will follow the mouse arrow with some smooth speed, we can achieve this effect y using p5.js.

It is a powerful JavaScript library for creating interactive graphics and animations in a web browser.



Approach: 

 



Used Functions: These are the list of all the functions and variables used in the example code.

This approach allows you to create a smooth animation where the object smoothly moves toward the mouse pointer. The draw function is called repeatedly by P5.js, so the position of the object can be updated on each iteration to create the animation.

Example: In this example, we can see how we can actually make the object follow the mouse pointer.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
  
        // Shape of the object is a circle
        let ball;
  
        let x = 0;
        let y = 0;
        // This method is used for creating canvas
        function setup() {
            createCanvas(windowWidth, windowHeight);
        }
  
        // This method will draw the circle 
        // and track the mouse as well.
        function draw() {
            background(255);
            x += (mouseX - x) * 0.04;
            y += (mouseY - y) * 0.04;
            fill(0);
            ellipse(x, y, 50, 50);
        }
    </script>
</head>
  
<body>
    <main>
        <h1 style="color: Green;">GeeksforGeeks</h1>
    </main>
</body>
  
</html>

Output:

 


Article Tags :