Implementation of canvas following mouse colorful ball

Time:2021-10-8

Follow the mouse colorful ball

Canvas didn’t disappoint me. It’s really interesting

Realization effect

Super cool

在这里插入图片描述

Implementation principle

  • Create a ball
  • Add random color to the ball, random radius
  • Move the mouse and add a small ball through instantiation
  • The animation effect of the small ball is realized by calling the new method added to the prototype
  • The canvas is constantly updated by a timer

Implementation process

Create a ball

Create a function to store all the styles of the ball, and then pass the current position of the mouse to the user by instantiating the functionBallFunction to instantiate the created ball, and finally store the created ball in the array. The array stores the attributes and attribute values of each ball in the form of an object

function Ball(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = getRandom();// Randomly generated color
    this.dx = parseInt(Math.random() * 10) - 5;// Generate randomly moved positions
    this.dy = parseInt(Math.random() * 10) - 5;//`- 5 'is to make the ball move around randomly
    ballArr.push(this);// Add ball
}
//Monitor mouse movement events
canvas.addEventListener('mousemove', function (e) {
    new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20));
    /*Instantiate ball as a ball object__ proto__ To call the prototype's methods*/
})

Generate random colors

aboutcolorThis property can represent a color by a 6-bit hexadecimal value

Therefore, a 6-bit hexadecimal number can be randomly generated as a random color

take0 to fThese 16 numbers are stored in the array and 6 are randomly generated0 to 16The index value of the array. In this way, you can randomly obtain 6 to through the index number of the array0 to fThe number in the

splitThe function of is to split a string and return an array with the parameters in parentheses as flags

//Set random color
function getRandom() {
    var allType = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f';// Hex color
    var allTypeArr = allType.split(',');// Split into arrays by ','
    var color = '#';
    for (var i = 0; i < 6; i++) {
        //Randomly generate a number from 0 to 16
        var random = parseInt(Math.random() * allTypeArr.length);
        color += allTypeArr[random];
    }
    return color;// Returns a randomly generated color
}

Render ball

Add to the prototype chain of the functionrenderMethod, let each passBallFunction, with these methods

The function is to passBallThe parameter of generates a circle. When instantiated, an object will be generated, which is stored in the objectx,y,rThese values

Ball.prototype.render = function () {
    ctx.beginPath();// Path start
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);// Draw circle, position, radius
    ctx.fillStyle = this.color;// colour
    ctx.fill();// fill
}

Update ball information

Because the generated ballx,y,rIs fixed, so the position of the ball is also fixed and will not change

Therefore, you need to change the position and radius of each small ball to make the small ball move. When the radius of the small ball is less than 0, callremoveMethod to delete the ball from the array

/*Clear when the update ball position and radius are less than 0*/
Ball.prototype.update = function () {
    this.x += this.dx;// X change
    this.y += this.dy;// Y change
    this.r -= 0.1;// Radius reduction
    if (this.r < 0) {
        this.remove();// Call the remove method you added
    }
}

Delete ball

This is called aboveremoveMethod, when this, that is, the radius of the current small ball is less than 0, I, traverse the entire array, find this, that is, the “small ball”, and delete the element of the array by calling the method in the array

The splice (index, Num) method deletes num elements starting from the index

Ball.prototype.remove = function () {
    for (var i = 0; i < ballArr.length; i++) {
        if (ballArr[i] == this) {
            ballArr.splice(i, 1);// Find the element less than 0 and delete it
        }
    }
}

Render canvas

Through the timer, constantly update the canvas, mainly these steps

  • Clear canvas
  • Traverse the array, get the information of all the small balls, and render them to the canvas
  • Keep calling repeatedly to update the ball information
setInterval(function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);// Clear screen
    for (var i = 0; i < ballArr.length; i++) {
        ballArr[i].update();// Update ball
        if (ballArr[i]) {
            ballArr[i].render();// Render ball
        }
    }
}, 20);

Complete code

<!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>Document</title>
    <style>
        body {
            background: black;
        }
        canvas {
            display: block;
            border: 1px solid black;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <canvas width="1000px" height="1000px" id="myCanvas">
        The current browser version does not support, please upgrade your browser
    </canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        //Defines the position and radius of the ball
        function Ball(x, y, r) {
            this.x = x;
            this.y = y;
            this.r = r;
            this.color = getRandom();// Randomly generated color
            this.dx = parseInt(Math.random() * 10) - 5;// Generate randomly moved positions
            this.dy = parseInt(Math.random() * 10) - 5;
            ballArr.push(this);// Add ball
        }
        /*Clear when the update ball position and radius are less than 0*/
        Ball.prototype.update = function () {
            this.x += this.dx;
            this.y += this.dy;
            this.r -= 0.1;
            if (this.r < 0) {
                this.remove();// Call the remove method you added
            }
        }
        Ball.prototype.remove = function () {
            for (var i = 0; i < ballArr.length; i++) {
                if (ballArr[i] == this) {
                    ballArr.splice(i, 1);// Find the element less than 0 and delete it
                }
            }
        }
        //Render ball draw ball
        //Add method to prototype
        Ball.prototype.render = function () {
            ctx.beginPath();// Path start
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);// Draw circle, position, radius
            ctx.fillStyle = this.color;// colour
            ctx.fill();
        }
        //Monitor mouse movement events
        canvas.addEventListener('mousemove', function (e) {
            new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20));
            //Instantiate ball as a ball object__ proto__ To call the prototype's methods
            console.log(ballArr);
        })
        var ballArr = [];
        setInterval(function () {
            ctx.clearRect(0, 0, canvas.width, canvas.height);// Clear screen
            for (var i = 0; i < ballArr.length; i++) {
                ballArr[i].update();// Update ball
                if (ballArr[i]) {
                    ballArr[i].render();// Render ball
                }
            }
        }, 20);
        //Set random color
        function getRandom() {
            var allType = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f';// Hex color
            var allTypeArr = allType.split(',');// Split into arrays by ','
            var color = '#';
            for (var i = 0; i < 6; i++) {
                var random = parseInt(Math.random() * allTypeArr.length);
                //Randomly generate a number from 0 to 16
                color += allTypeArr[random];
            }
            return color;// Returns a randomly generated color
        }
    </script>
</body>

</html>

This is the end of this article about the implementation of canvas following the mouse colorful ball. For more information about canvas following the mouse, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!