DEV Community

Cover image for Click to generate crazy particles - with Canvas
SamrithaS
SamrithaS

Posted on • Edited on

3 1

Click to generate crazy particles - with Canvas

Let's use HTML Canvas to generate crazy particles on clicking.

Check it out here:

STEPS

The HTML file contains <canvas></canvas> that would create a canvas element.

The rest of the code belongs to the JS file.
Now that we have the canvas element,

const canvas = document.querySelector("canvas");
const c = canvas.getContext("2d");
canvas.style.background = "black";
Enter fullscreen mode Exit fullscreen mode

This helps us get the canvas element from the DOM,const c = canvas.getContext("2d") defines the drawing context of the canvas which is 2D and canvas.style.background = "black sets a background color to it.

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize", () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});
Enter fullscreen mode Exit fullscreen mode

Now, we are setting the window's width and height to the canvas's width and height respectively, also making sure that when the window is resized, the width and height are in sync.

Let's create a class named Circle which would help us generate the circular particles on clicking,

class Circle {
    constructor(x, y, color, radius) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.radius = radius;
    }
    draw() {
        c.beginPath();
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        c.fillStyle = this.color;
        c.fill();
        c.closePath();
    }
    update() {
        this.draw();
        this.x += Math.random() * 8 - 4;
        this.y += Math.random() * 8 - 4;
    }
}
Enter fullscreen mode Exit fullscreen mode

The parameters of the class are x, y, color and radius corresponding to positions, color and radius of the circle.
There are two methods in the class: draw() and update(),
draw method will help us draw a circle using beginPath()
which would begin drawing a path in the canvas and c.arc(x, y, radius, startAngle, endAngle [, counterclockwise]) will help us create an arc, this would take x, y, radius, startAngle, endAngle and counterclockwise(boolean) arguments.

update() is the method that makes the circle particles act a bit crazy by updating the x and y positions of the particles, making it move around a bit.

let prevX;
let prevY;
let circles = [];
document.addEventListener("click", () => {
    clientx = window.event.clientX;
    clienty = window.event.clientY;
    for (let i = 0; i < 10; i++) {
        const x = Math.random() * i * 20 + clientx;
        const y = Math.random() * i * 20 + clienty;
        const radius = Math.random() * 5;
        let val = i * 200 * Math.random() * clienty;
        let perc = Math.random() * 90;
        let color = `hsl(${val}, ${perc}%, 60%)`;
        let rad = Math.random() * 20;
        circles.push(new Circle(x, y, color, rad));
    }
    animate();
});
Enter fullscreen mode Exit fullscreen mode

After adding a click event listener, window.event.clientX and window.event.clientY gives us the vertical and horizontal coordinates of the mouse pointer.
Since I want 10 circles to be generated on each click, I have a loop running from 0 to 10, and each of the circles would have different positions, colors and sizes with the help of Math.random(). Next we'll be creating an instance of the class Circle and pushing these instances into the 'circles' array. Finally, the animate function will be called which is:

function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, canvas.width, canvas.height);
    circles.forEach((circle) => {
        circle.update();
    });
}
Enter fullscreen mode Exit fullscreen mode

requestAnimationFrame tells the browser that we wish to perform an animation, it takes a callback function, in our case it's the animate function itself - it would be called recursively creating the crazy effect we need.
Last but not the least, for each element of the 'circles' array, which contains all the instances of circles created, we would call the update() method.
Notice that, the update method calls the draw method itself which is why we haven't called it elsewhere. So the update method draws a circle and also updates it's position everytime the animate function is called.

and that's about it.

Thank you for coming this far, hope you loved the blog as much as I loved writing it.
Here's where we can connect:

instagram: https://www.instagram.com/artzy_artoholic/
twitter: https://twitter.com/Samritha22
codepen: https://codepen.io/samritha

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more