先来看看最终效果:
源码奉上:(因为是整个网页都使用该背景,所以只需要引入JS就可以)
js代码:
1 ! function() { 2 function n(n, e, t) { 3 return n.getAttribute(e) || t 4 } 5 6 function e(n) { 7 return document.getElementsByTagName(n) 8 } 9 10 function t() { 11 var t = e("script"), 12 o = t.length, 13 i = t[o - 1]; 14 return { 15 l: o, 16 z: n(i, "zIndex", -1), 17 o: n(i, "opacity", .5), 18 c: n(i, "color", "0,0,0"), 19 n: n(i, "count", 99) 20 } 21 } 22 23 function o() { 24 a = m.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, c = m.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight 25 } 26 27 function i() { 28 r.clearRect(0, 0, a, c); 29 var n, e, t, o, m, l; 30 s.forEach(function(i, x) { 31 for(i.x += i.xa, i.y += i.ya, i.xa *= i.x > a || i.x < 0 ? -1 : 1, i.ya *= i.y > c || i.y < 0 ? -1 : 1, r.fillRect(i.x - .5, i.y - .5, 1, 1), e = x + 1; e < u.length; e += 1) { 32 n = u[e], null !== n.x && null !== n.y && (o = i.x - n.x, m = i.y - n.y, l = o * o + m * m, l < n.max && (n === y && l >= n.max / 2 && (i.x -= .03 * o, i.y -= .03 * m), t = (n.max - l) / n.max, r.beginPath(), r.lineWidth = t / 2, r.strokeStyle = "rgba(" + d.c + "," + (t + .2) + ")", r.moveTo(i.x, i.y), r.lineTo(n.x, n.y), r.stroke())) 33 } 34 }), x(i) 35 } 36 var a, c, u, m = document.createElement("canvas"), 37 d = t(), 38 l = "c_n" + d.l, 39 r = m.getContext("2d"), 40 x = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(n) { 41 window.setTimeout(n, 1e3 / 45) 42 }, 43 w = Math.random, 44 y = { 45 x: null, 46 y: null, 47 max: 2e4 48 }; 49 m.id = l, m.style.cssText = "position:fixed;top:0;left:0;z-index:" + d.z + ";opacity:" + d.o, e("body")[0].appendChild(m), o(), window.onresize = o, window.onmousemove = function(n) { 50 n = n || window.event, y.x = n.clientX, y.y = n.clientY 51 }, window.onmouseout = function() { 52 y.x = null, y.y = null 53 }; 54 for(var s = [], f = 0; d.n > f; f += 1) { 55 var h = w() * a, 56 g = w() * c, 57 v = 2 * w() - 1, 58 p = 2 * w() - 1; 59 s.push({ 60 x: h, 61 y: g, 62 xa: v, 63 ya: p, 64 max: 6e3 65 }) 66 } 67 u = s.concat([y]), setTimeout(function() { 68 i() 69 }, 100) 70 }();
引自:https://www.seoblogs.cn/seogj/2018620.html