效果如下
其中红色的“线条精灵”所实现的是根据鼠标的移动轨迹,可以“滚动追随”。整体的效果还是十分酷炫的,大家可以自己去尝试一下哦!
代码
index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>酷炫雪花特效_追光者♂</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
style.css
canvas{
position:absolute;
top:0;
left:0;
}
index.js
$(document).ready(function() {
var W = window.innerWidth,
H = window.innerHeight,
particleCount = 200,
particles = [],
minDist = 120,
dist,
bgColor = "rgba(150,82,81,1)",
dotColor = "#fff",
xSpeed = 5,
ySpeed = 5,
dotSize = 13;
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = W;
canvas.height = H;
function paintCanvas() {
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, W, H);
}
function Particle() {
this.x = Math.random() * W;
this.y = Math.random() * H;
this.vx = -1 + Math.random() * (Math.random() * xSpeed);
this.vy = -1 + Math.random() * (Math.random() * ySpeed);
this.radius = Math.random() * (Math.random() * dotSize);
this.draw = function() {
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
}
}
for (var i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
function draw() {
paintCanvas();
for (var i = 0; i < particles.length; i++) {
p = particles[i];
p.draw();
}
update();
}
function update() {
for (var i = 0; i < particles.length; i++) {
p = particles[i];
p.x += p.vx;
p.y += p.vy;
if (p.x + p.radius > W)
p.x = p.radius;
else if (p.x - p.radius < 0) {
p.x = W - p.radius;
}
if (p.y + p.radius > H)
p.y = p.radius;
else if (p.y - p.radius < 0) {
p.y = H - p.radius;
}
for (var j = i + 1; j < particles.length; j++) {
p2 = particles[j];
distance(p, p2);
}
}
}
var mouse = {
x: 0,
y: 0
};
document.addEventListener('mousemove', function(e) {
mouse.x = e.clientX || e.pageX;
mouse.y = e.clientY || e.pageY;
console.log(mouse.x, mouse.y);
}, false);
function distance(p1, p2) {
var dist,
dx = p1.x - mouse.x;
var dy = p1.y - mouse.y;
dist = Math.sqrt((dx * dx) + (dy * dy));
if (dist <= minDist) {
ctx.beginPath();
ctx.strokeStyle = "rgba(255,82,81," + (1.2 - (dist / minDist) / Math.random()) + ")";
ctx.lineWidth = 1;
ctx.moveTo(mouse.x, mouse.y);
ctx.lineTo(p1.x, p1.y);
ctx.stroke();
ctx.closePath();
var ax = dy / 50000,
ay = dy / 50000;
p1.vx -= ax;
p1.vy -= ay;
}
}
function animloop() {
draw();
requestAnimFrame(animloop);
}
animloop();
});
以上即为全部源代码,大家可以去运行实现啦!
另外,整个的源文件我也将上传到“资源
”中,热烈欢迎大家下载!