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

Bootstrap FileInput implements image upload function

This article example shares the specific code of ...

HTML simple web form creation example introduction

<input> is used to collect user information ...

XHTML Getting Started Tutorial: Form Tags

<br />Forms are an important channel for use...

JavaScript design pattern chain of responsibility pattern

Table of contents Overview Code Implementation Pa...

Implementation of CSS loading effect Pac-Man

emmm the name is just a random guess 2333 Preface...

Vue implements an example of pulling down and scrolling to load data

Table of contents Step 1: Installation Step 2: Ci...

How to enable Swoole Loader extension on Linux system virtual host

Special note: Only the Swoole extension is instal...

Summary of some common methods of JavaScript array

Table of contents 1. How to create an array in Ja...

Vue custom bullet box effect (confirmation box, prompt box)

This article example shares the specific code of ...

HTML table only displays the outer border of the table

I would like to ask a question. In Dreamweaver, I...

MySQL joint table query basic operation left-join common pitfalls

Overview For small and medium-sized projects, joi...

The perfect solution for highlighting keywords in HTML

I recently encountered a feature while working on...

Summary of some common uses of refs in React

Table of contents What are Refs 1. String type Re...