How to use ES6 class inheritance to achieve a gorgeous ball effect

How to use ES6 class inheritance to achieve a gorgeous ball effect

introduce

This effect is drawn with Canvas and then implemented using class inheritance. When the mouse moves at the specified Canvas position, a small ball of random color will be generated at the current mouse position, and then the ball will slowly disappear.

Effect diagram

Implementation steps

  • Writing HTML
  • Create a canvas environment
  • Writing Ball
  • Implement the MoveBall class that inherits the Ball class
  • Instantiate the ball

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Beautiful Balls</title>
    <style>
        #canvas{
            margin-left: 100px
        }
    </style>
</head>
<body>
    <canvas id="canvas">Your browser does not support canvas</canvas>

    <!-- <script src="./underscore-min.js"></script> -->
    <!-- Underscore already has a packaged _.random function. You don't need to write a random function manually by importing it. -->
    <script src="./index.js"></script>
</body>
</html>

Create a canvas environment

 // index.js
 
 // 1. Get the current canvas const canvas = document.getElementById('canvas');
 const ctx = canvas.getContext('2d');
  
 // Set the canvas size style canvas.width = 1000;
 canvas.height = 600;
 canvas.style.backgroundColor = '#000'

Example analysis

First, find the canvas element:

const canvas = document.getElementById("myCanvas");

Then, create the context object:

const ctx = canvas.getContext('2d');

Set the width and height background color

Writing Ball

// index.js

 // 2. Ball class class Ball {
     constructor (x, y, color) {
         this.x = x; // x-axis this.y = y; // y-axis this.color = color; // color of the ball this.r = 40; // radius of the ball }
 
     // Draw the ball render () {
         ctx.save();
         ctx.beginPath();
         ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
         ctx.fillStyle = this.color;
         ctx.fill();
         ctx.restore();
     }
 }

Example analysis

  • You can see that there is a constructor() method, which is the construction method, and the this keyword represents the instance object.
  • save() ---- Save the current state of the environment
  • beginPath() ---- Start a path, or reset the current path
  • arc() ---- used to create arcs/curves (used to create circles or partial circles) -- parameters are as follows
parameter describe
x The x-coordinate of the center of the circle.
y The y coordinate of the center of the circle.
r The radius of the circle.
sAngle The starting angle, in radians (the three o'clock position of the arc circle is 0 degrees).
eAngle The ending angle, in radians.
counterclockwise Optional. Specifies whether drawing should be counterclockwise or clockwise. False = clockwise, true = counterclockwise.
  • fillStyle() ---- Sets or returns the color, gradient, or pattern used to fill a painting.
  • fill() ---- Fill the current drawing (path)
  • restore() ---- Returns the previously saved path status and properties.

Implement the MoveBall class that inherits the Ball class

// index.js

// 3. Class that moves the ball class MoveBall extends Ball { // Inherits constructor (x, y, color) {
        super(x, y, color);

        // Change in quantity // Random coordinates of the ball this.dX = Random(-5, 5);
        this.dY = Random(-5, 5);
        // Random number for decreasing radius, because the ball starts out large and then slowly disappears this.dR = Random(1, 3);
    }

    // 4. Change the position and radius of the ball upDate () {
        this.x += this.dX;
        this.y += this.dY;
        this.r -= this.dR;
        // Determine whether the radius of the ball is less than 0
        if(this.r < 0) {
            this.r = 0 // A radius of 0 means the ball disappears}
    }
}

Example analysis

  • A MoveBall class is defined here, which inherits all the properties and methods of the Ball class through the extends keyword.
  • The super keyword, which here represents the constructor of the parent class, is used to create a new this object of the parent class. The subclass must call the super method in the constructor method, otherwise an error will be reported when creating a new instance. This is because the subclass's own this object must first be shaped by the parent class's constructor to obtain the same instance properties and methods as the parent class, and then processed and added with the subclass's own instance properties and methods. If the super method is not called, the subclass will not get the this object. (Click here for details)
  • The purpose of the upDate method is to change the position and radius of the ball, and make different changes according to the position of the mouse

Instantiate the ball

// index.js

// 5. Instantiate the ball // Store the generated ball let ballArr = [];

// Define random function If you reference underscore-min.js, you don't need to write a random function, you can directly use _.random
let Random = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min);
}

// Listen for mouse movement canvas.addEventListener('mousemove', function (e){
    // Random colors // You can also use a fixed color array let colorArr = ['red', 'green', 'blue', 'yellow', 'orange', 'pink'];
    // bgcolor ==> colorArr[Random(0, colorArr.length - 1)]
    let bgColor = `rgb(${Random(0,256)}, ${Random(0,256)}, ${Random(0,256)})`;
    ballArr.push(new MoveBall(e.offsetX, e.offsetY, bgColor));
    console.log(ballArr);
})

// Start the timer setInterval(function () {

    // Clear the screen ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the ball for (let i = 0 ; i < ballArr.length; i++ ) {
        ballArr[i].render();
        ballArr[i].upDate();
    }
}, 50);

Example analysis

  • Wrote a Random function for generating random colors
  • Listen to the movement of the mouse to create a moving ball, and then push it into the array that stores the balls. In this way, the balls in the array have render and update methods. Finally, call the render method of the Ball class in turn to draw it, and call the update method of MoveBall. Now the effect comes out!
  • clearRect clearing operation----Clears the specified pixels within the given rectangle (click for details). See the picture below for the effect of not clearing the screen

We can see that the radius of the ball that does not clear the screen gradually shrinks, but the ball will not disappear in the end. This is definitely not the effect we want! What is the effect of clearing the screen? It’s the effect at the beginning of the article! (Baby, have fun❤)

index.js full code

// 1. Get the current canvas const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Set the canvas size style canvas.width = 1000;
canvas.height = 600;
canvas.style.backgroundColor = '#000'

// 2. Ball class class Ball {
    constructor (x, y, color) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.r = 40;
    }

    // Draw the ball render () {
        ctx.save();
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.restore();
    }

}

// 3. Class that moves the ball class MoveBall extends Ball { // Inherits constructor (x, y, color) {
        super(x, y, color);

        // Change in quantity // Random coordinates of the ball this.dX = Random(-5, 5);
        this.dY = Random(-5, 5);
        // Random number with smaller radius this.dR = Random(1, 3);
    }

    // 4. Change the position and radius of the ball upDate () {
        this.x += this.dX;
        this.y += this.dY;
        this.r -= this.dR;
        // Determine whether the radius of the ball is less than 0
        if(this.r < 0) {
            this.r = 0
        }
    }

}

// 5. Instantiate the ball // Store the generated ball let ballArr = [];

// Define random function If you reference underscore-min.js, you don't need to write a random function, you can directly use _.random
let Random = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min);
}

// Listen for mouse movement canvas.addEventListener('mousemove', function (e){
    // Random colors // You can also use a fixed color array let colorArr = ['red', 'green', 'blue', 'yellow', 'orange', 'pink'];
    // bgcolor ==> colorArr[Random(0, colorArr.length - 1)]
    let bgColor = `rgb(${Random(0,256)}, ${Random(0,256)}, ${Random(0,256)})`;
    ballArr.push(new MoveBall(e.offsetX, e.offsetY, bgColor));
    console.log(ballArr);
})

// Start the timer setInterval(function () {

    // Clear the screen ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the ball for (let i = 0 ; i < ballArr.length; i++ ) {
        ballArr[i].render();
        ballArr[i].upDate();
    }
}, 50);

Summarize

I hope this little demo can help you become more familiar with the understanding and use of classes in ES6. This is the end of this article on how to use ES6 class inheritance to achieve the effect of gorgeous small balls. For more relevant content about ES6 class inheritance to achieve small balls, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Analysis of concepts and usage of ES6 new features such as Class and Extends
  • Detailed example of Class inheritance usage in ES6 javascript
  • ES6 class chain inheritance, instantiation and react super (props) principle detailed explanation

<<:  Summary of Linux sftp command usage

>>:  Mysql varchar type sum example operation

Blog    

Recommend

Detailed explanation of the role of key in React

Table of contents Question: When the button is cl...

MYSQL local installation and problem solving

Preface This article is quite detailed and even a...

How to track users with JS

Table of contents 1. Synchronous AJAX 2. Asynchro...

Docker image access to local elasticsearch port operation

Using the image service deployed by docker stack,...

Encapsulate a simplest ErrorBoundary component to handle react exceptions

Preface Starting from React 16, the concept of Er...

jQuery implements the function of adding and deleting employee information

This article shares the specific code of jQuery t...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...

We're driving IE6 to extinction on our own

In fact, we wonder every day when IE6 will really...

Vue implements multi-tab component

To see the effect directly, a right-click menu ha...

How to draw special graphics in CSS

1. Triangle Border settings Code: width: 300px; h...

Basic knowledge of website design: newbies please read this

Now many people are joining the ranks of website ...

Usage and principles of provide and inject in Vue3

Preface: When passing data between parent and chi...

Example of how to reference environment variables in Docker Compose

In a project, you often need to use environment v...

How to use JavaScript strategy pattern to validate forms

Table of contents Overview Form validation withou...

Navicat remote connection to MySQL implementation steps analysis

Preface I believe that everyone has been developi...