七仔的博客

七仔的博客GithubPages分博

0%

炫酷的博客背景

使用JavaScript实现,生成150个点,然后使用嵌套的for循环来判断每两个点之间是否需要连线以及连线的透明度

炫酷的博客背景

看看博客周围,游动的点连成线,构成一幅动态的背景努力(现在可能看不到,有可能切换到别的特效了)

特效截图

原理:

使用JavaScript实现,生成150个点,然后使用嵌套的for循环来判断每两个点之间是否需要连线以及连线的透明度。

这是基本原理,后面我又改了一版是因为占用CPU有点高,改到了每秒30帧,现在在我的电脑上运行可以降到10%的CPU利用率,之前是30%拍头

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const canvas = document.getElementById("myCanvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
const ctx = canvas.getContext("2d");

//创建小球的构造函数
function Ball() {
this.x = randomNum(3, canvas.width - 3);
this.y = randomNum(3, canvas.height - 3);
this.r = randomNum(1, 3);
this.color = "rgb(0,0,0)";
//小球速度
this.speedX = randomNum(-3, 3) * 0.6;
this.speedY = randomNum(-3, 3) * 0.6;
}

Ball.prototype = {
//绘制小球
draw: function() {
ctx.beginPath();
ctx.globalAlpha = 0.4;
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
},
//小球移动
move: function() {
this.x += this.speedX;
this.y += this.speedY;
//为了合理性,设置极限值
if (this.x <= 3 || this.x > canvas.width - 3) {
this.speedX *= -1;
}
if (this.y <= 3 || this.y >= canvas.height - 3) {
this.speedY *= -1;
}
}
};
//存储所有的小球
const balls = [];
//创建n个小球
const n = 150;
for (let i = 0; i < n; i++) {
const ball = new Ball();
balls.push(ball);
}

main();
function main() {
//电脑才有特效
if(canvas.width > 1000){
let step = (timestamp, elapsed) => {
//一秒30帧
if (elapsed > 1000 / 30) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//小球与小球之间自动画线
drawLine();
elapsed = 0
}

window.requestAnimationFrame(
_timestamp => step(_timestamp, elapsed + _timestamp - timestamp)
)
};
window.requestAnimationFrame(timestamp => step(timestamp, 0))
}
}

//添加鼠标移动事件
//记录鼠标移动时的mouseX坐标
let mouseX;
let mouseY;
canvas.onmousemove = function(e) {
const ev = event || e;
mouseX = ev.offsetX;
mouseY = ev.offsetY;
};

//判断是否划线
function drawLine() {
let distance;
for (let i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].move();
for (let j = 0; j < balls.length; j++) {
if (i !== j) {
distance = Math.sqrt(Math.pow((balls[i].x - balls[j].x), 2) + Math.pow((balls[i].y - balls[j].y), 2));
if (distance < 130) {
ctx.beginPath();
ctx.moveTo(balls[i].x, balls[i].y);
ctx.lineTo(balls[j].x, balls[j].y);
ctx.strokeStyle = "rgba(0,0,0," + (1 - distance / 130) + ")";
ctx.stroke();
}
}
}
}
}

//随机函数
function randomNum(m, n) {
return Math.floor(Math.random() * (n - m + 1) + m);
}

html中要加一个canvas

1
<canvas class="background" id="myCanvas"></canvas>

还有引用

1
<script src="js/background.js"></script>

再加个css样式

1
2
3
4
5
/*背景*/
.background{
position:fixed;
z-index:-1;
}

就可以看到酷炫的粒子背景啦上升

此为博主副博客,留言请去主博客,转载请注明出处:https://www.baby7blog.com/myBlog/24.html

欢迎关注我的其它发布渠道