Using js to realize dynamic background

Using js to realize dynamic background

This article example shares the specific code of js to realize dynamic background for your reference. The specific content is as follows

1. Copy the following code and save it as a js file

window.onload = function () {
    //Define the body's margin from the default value 8px->0px
    document.body.style.margin = "0";
    document.body.style.background = "#30333F";
    //Create canvas document.body.appendChild(document.createElement('canvas'));
    var canvas = document.querySelector('canvas'),
        ctx = canvas.getContext('2d') //ctx returns an api/dom for drawing on canvas
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.style.position = 'fixed';
    ctx.lineWidth = .3;
    ctx.strokeStyle = (new Color(150)).style;
    //Define the mouse coverage range var mousePosition = {
        x: 30 * canvas.width / 100,
        y: 30 * canvas.height / 100
    };
    var dots = {
        nb: 1000, //Total number of Dots distance: 50,
        d_radius: 100,
        array: []
    };
    //Create a color class, the Color class returns a string type rgba (*,*,*,.8)
    function mixComponents(comp1, weight1, comp2, weight2) {
        return (comp1 * weight1 + comp2 * weight2) / (weight1 + weight2);
    }
    function averageColorStyles(dot1, dot2) {
        var color1 = dot1.color,
            color2 = dot2.color;

        var r = mixComponents(color1.r, dot1.radius, color2.r, dot2.radius),
            g = mixComponents(color1.g, dot1.radius, color2.g, dot2.radius),
            b = mixComponents(color1.b, dot1.radius, color2.b, dot2.radius);
        return createColorStyle(Math.floor(r), Math.floor(g), Math.floor(b));
    }
    function colorValue(min) {
        return Math.floor(Math.random() * 255 + min);
    }
    function createColorStyle(r, g, b) {
        return 'rgba(' + r + ',' + g + ',' + b + ', 0.8)';
    }
    function Color(min) {
        min = min || 0;
        this.r = colorValue(min);
        this.g = colorValue(min);
        this.b = colorValue(min);
        this.style = createColorStyle(this.r, this.g, this.b);
    }
    //Create the Dot class and a series of methods function Dot() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;

        this.vx = -.5 + Math.random();
        this.vy = -.5 + Math.random();

        this.radius = Math.random() * 2;

        this.color = new Color();
    }

    Dot.prototype = {
        draw: function () {
            ctx.beginPath();
            ctx.fillStyle = this.color.style;
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
            ctx.fill();
        }
    };
    function moveDots() { //Movement of Dot object for (i = 0; i < dots.nb; i++) {

            var dot = dots.array[i];

            if (dot.y < 0 || dot.y > canvas.height) {
                dot.vx = dot.vx;
                dot.vy = - dot.vy;
            }
            else if (dot.x < 0 || dot.x > canvas.width) {
                dot.vx = - dot.vx;
                dot.vy = dot.vy;
            }
            dot.x += dot.vx;
            dot.y += dot.vy;
        }
    }
    function connectDots() { //Connection of DOt objects for (i = 0; i < dots.nb; i++) {
            for (j = i; j < dots.nb; j++) {
                i_dot = dots.array[i];
                j_dot = dots.array[j];

                if ((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > - dots.distance && (i_dot.y - j_dot.y) > - dots.distance) {
                    if ((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > - dots.d_radius && (i_dot.y - mousePosition.y) > - dots.d_radius) {
                        ctx.beginPath();
                        ctx.strokeStyle = averageColorStyles(i_dot, j_dot);
                        ctx.moveTo(i_dot.x, i_dot.y);
                        ctx.lineTo(j_dot.x, j_dot.y);
                        ctx.stroke();//Draw the defined route ctx.closePath();//Create a path from the current point back to the starting point}
                }
            }
        }
    }
    function createDots() {//Create nb Dot objects for (i = 0; i < dots.nb; i++) {
            dots.array.push(new Dot());
        }
    }
    function drawDots() { //reference the Dot prototype chain, use the draw method, and draw the Dot object on the canvas for (i = 0; i < dots.nb; i++) {
            var dot = dots.array[i];
            dot.draw();
        }
    }
    function animateDots() {
        ctx.clearRect(0, 0, canvas.width, canvas.height); //Clear the canvas, otherwise the lines will be connected moveDots();
        connectDots();
        drawDots();
        requestAnimationFrame(animateDots);
    }
    createDots(); //Use to create Dot class function requestAnimationFrame(animateDots); //Use canvas's unique 60Hz refresh screen canvas method document.querySelector('canvas').addEventListener('mousemove', function (e) {
        mousePosition.x = e.pageX;
        mousePosition.y = e.pageY;
    })

    document.querySelector('canvas').addEventListener('mouseleave', function (e) { //When the mouse leaves, the connection automatically returns to the center of the canvas mousePosition.x = canvas.width / 2;
        mousePosition.y = canvas.height / 2;
    })

}

2. Then import the js file into the HTML page that needs to use the dynamic background

The effect is as follows:

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS canvas dynamically realizes the background effect of The Matrix
  • JS realizes dynamic starry sky background effect
  • JS dynamically changes the background color of the web page body example code
  • Create a super cool particle dynamic background effect based on Particles.js (imitating Zhihu)
  • How to dynamically modify the background color using JavaScript
  • Method to realize dynamic rain background effect generated by JavaScript
  • JS code to dynamically change the background color of the web page when the mouse is selected

<<:  Introduction to Spark and comparison with Hadoop

>>:  The standard HTML writing method is different from the one automatically generated by Dreamweaver

Recommend

How to quickly insert 10 million records into MySQL

I heard that there is an interview question: How ...

Should I use distinct or group by to remove duplicates in MySQL?

Preface About the performance comparison between ...

JavaScript data structure bidirectional linked list

A singly linked list can only be traversed from t...

A brief introduction to MySQL dialect

Putting aside databases, what is dialect in life?...

Detailed tutorial on installing mysql under Linux

1. Shut down the mysql service # service mysqld s...

How to use Docker to build a pypi private repository

1. Construction 1. Prepare htpasswd.txt file The ...

Understand the principle of page replacement algorithm through code examples

Page replacement algorithm: The essence is to mak...

js data types and their judgment method examples

js data types Basic data types: number, string, b...

Javascript common higher-order functions details

Table of contents 1. Common higher-order function...

MySQL Index Detailed Explanation

Table of contents 1. Index Basics 1.1 Introductio...

MySQL table field time setting default value

Application Scenario In the data table, the appli...

SQL GROUP BY detailed explanation and simple example

The GROUP BY statement is used in conjunction wit...

Solution to leaving gaps between BootStrap grids

Table of contents [See an example]: [The original...