Popular dynamic background connection effects. The code below is organized and commented by the author on the extracted code, which is very suitable for reference learning.
Effect screenshot:
Effect demonstration: https://jc1144096387.github.io/canvas_nest/
Author address: https://blog.csdn.net/u013556477/article/details/82819785
HTML code (test code):
<!doctype html><html lang=en> <head> <meta charset=UTF-8> <meta name=Generator content=EditPlus®> <meta name=Author content=> <meta name=Keywords content=> <meta name=Description content=> <title>Canvas scene connection effects</title> <style type=text/css>*{ margin: 0px; padding: 0px; } body{ background-color: #f4f4f4; }</style></head><body> <!-- <canvas id=c_n9 width=1366 height=403 style=position: fixed; top: 0px; left: 0px ; z-index: -1; opacity: 0.5;></canvas> --> <script type=text/javascript src=test-clear.js opacity=0 .6></script></body></html>
Javascript code:
//Execute the function immediately //! is used to tell the JavaScript engine that this is a function expression, not a function declaration, (),! , +, - and other operators can achieve this effect, but () is the safest // Adding () after !function(){} will call the function immediately // This can simulate a private scope, In this way, the html file will not cause variable conflicts when referencing multiple js files! function() { //Canvas element related // Create a canvas element and set the id of the canvas element var canvas = document.createElement(canvas), context = canvas .getContext(2d), attr = getAttr(); //Set the related attributes of the created canvas canvas.id = c_n + attr.length; canvas.style.cssText = position:fixed;top:0;left:0;z-index: + attr.z + ;opacity: + attr.opacity; //Add the canvas element to the body element document.getElementsByTagName(body)[0].appendChild(canvas); //This function sets the width attribute and height attribute of the canvas element getWindowWH(); //The onresize event will occur when the window or frame is resized //Here is when the window size changes, the width and height of the window are reacquired And set the width and height of the canvas element window.onresize = getWindowWH; //This function will get the script element that references this file. //Because the getScript function is executed once during assignment in this file, when the html file refers to this file, the script tag after this file has not been interpreted by the browser. //So in the script array obtained, the script element that references this article is at the end of the array //The purpose of this function is to enable developers to directly modify the attributes of the script element that introduces the file into HTML to modify some properties of the canvas. , the z-index of the canvas, the transparency and the number of small squares, the color // Cooperate with the previous code to add the canvas element to the body element. When the developer wants to use this special effect as the background, he only needs to add the script element to the html file and Just quote this file function getAttr() { let scripts = document.getElementsByTagName(script), len = scripts.length, script = scripts[len - 1]; //v is the last script element, which refers to the script element of this document return { length: len, z: script.getAttribute (zIndex) || -1, opacity: script.getAttribute(opacity) || 0.5, color: script.getAttribute(color) || 0,0,0, count: script.getAttribute(count) || 99 } } //Get the window width and height, and set the canvas element width and height function getWindowWH() { W = canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body .clientWidth, H = canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight } //Generate small squares at random positions var random = Math.random, squares = []; //Storage small squares//Put small squares into the squares[] array for (let p = 0; p < attr.count; p++) { var square_x = random() * W, //abscissa square_y = random() * H, //ordinate square_xa = 2 * random() - 1, //x-axis displacement-1,1 square_ya = 2 * random () - 1; //Y-axis displacement squares.push({ x: square_x, y: square_y, xa: square_xa, ya: square_ya, max: 6000 }) } //Generate a small mouse square var mouse = { x: null, y: null, max: 20000 }; //Get the coordinates of the mouse window.onmousemove = function(i) { //i is W3C DOM, window.event For IE DOM, to achieve compatibility with IE //However, it seems that IE currently supports W3C DOM. I am using IE11. I can also achieve mouse interaction effects by commenting out the next line of code. //It is said online that 7/8/9 is not supported. Yes, I have not tested it. //Of course it is correct to add i = i || window.event; mouse.x = i.clientX; mouse.y = i.clientY; } //After the mouse moves out of the window, remove the mouse Small square window.onmouseout = function() { mouse.x = null; mouse.y = null; } //Draw a small square, the small square moves (reverse movement when touching the boundary), the small square is bound by the mouse var animation = window.requestAnimationFrame || window .webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(i) { window.setTimeout(i, 1000 / 45) }; //The requestAnimationFrame supported by each browser is different, and it is compatible with each browser function draw() { //Clear the canvas context.clearRect(0, 0, W, H); var w = [mouse].concat (squares); //Connect (merge) the mouse small square array and other small square arrays var x, v, A, B, z, y; //square attribute table: x, y, xa, ya, max squares.forEach(function(i) { //Realize the directional movement of small squares ix += i.xa; iy += i.ya; //Control the movement direction of small squares//When the small square reaches the window boundary, move in the opposite direction i.xa = i.xa * (ix > W || ix < 0 ? -1 : 1); i.ya = i.ya * (iy > H || iy < 0 ? -1 : 1); //The first two parameters of fillRect are the x, y coordinates of the upper left corner of the rectangle, and the last two are the width and height respectively //Draw a small square context.fillRect(ix - 0.5, iy - 0.5, 1, 1); //Traverse All elements in w for (let n = 0; n < w.length; n++) { x = w[n]; //If x and i are not the same object instance and the xy coordinates of x exist if (i !== x && null !== xx && null !== xy) { x_diff = ix - xx; //The difference between the x coordinates of i and x y_diff = iy - xy; //The difference between the y coordinates of i and x distance = x_diff * x_diff + y_diff * y_diff; //Hypotenuse squared if (distance < x.max) { //Make the small square i be bound by the small square of the mouse, that is, if the distance between the small square i and the small square of the mouse is too large, the small square i will be bound by the small square of the mouse, //resulting in multiple small squares with the mouse as the center, mouse.max /2 is the radius to make a circle if (x === mouse && distance > x.max / 2) { ix = ix - 0.03 * x_diff; iy = iy - 0.03 * y_diff; } A = (x.max - distance) / x.max; context.beginPath(); //Set the thickness of the brush's line to be related to the distance between the two small squares, ranging from 0-0.5. The farther the distance between the two small squares, the thinner the line, reaching max The line disappears when the line is drawn context.lineWidth = A / 2; //Set the line color of the brush to sc, which is the canvas color, and the transparency to (A+0.2), that is, the farther away the two small squares are, the lighter the line is. context.strokeStyle = rgba ( + attr.color + , + (A + 0.2) + ); //Set the brush stroke to the i small square context.moveTo(ix, iy); //Move the brush stroke to the x small square context.lineTo(xx, xy); //Complete the drawing of the line, that is, drawing the line connecting the small squares context.stroke(); } } } //Remove small square i from w array //Prevent two small squares from being connected repeatedly w.splice(w.indexOf(i), 1); }); //window.requestAnimationFrame is similar to setTimeout, forming a recursive call , //However, window.requestAnimationFrame uses the system time interval to maintain the best drawing efficiency, and provides better optimization to make the animation smoother//After browser optimization, the animation is smoother; //When the window is not activated, the animation will stop to save computing resources; animation(draw); } //Here, after waiting for 0.1 seconds, execute draw() once. The real animation effect is setTimeout( implemented by window.requestAnimationFrame function() { draw(); }, 100)} ();
Source code address: https://github.com/jc1144096387/canvas_nest
SummarizeThe above is the code for parsing html5 canvas to achieve background mouse connection dynamic effects introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!
If you think this article is helpful to you, you are welcome to reprint it, please indicate the source, thank you!