效果图:
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="canvas" ></canvas>
<script type="text/javascript">
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
// 鼠标位置
var mouse = {
x : innerWidth/2,
y : innerHeight/2
}
// 监听鼠标位置
window.onmousemove = function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
}
// 窗口大小改变画布一起改变
window.onresize = function(){
canvas.width = innerWidth;
canvas.height = innerHeight;
}
// 随机生成颜色
function gc(){
var s = '0123456789abcdef';
var c = '#';
for (var i = 0; i < 6; i++) {
c += s[Math.floor(Math.random() * 15)];
}
return c;
}
//线条
function Linner(x,y,color,lineW,speet){
this.x = x;
this.y = y;
// 线的颜色
this.color = color;
// 线宽
this.lineW = lineW;
// 每次更新Linner对象位置所增加的弧度
this.speet = speet;
// 在开始的时候确定LInner对象的弧度0~2*PI
this.theta = Math.random()*Math.PI*2;
// 在鼠标移入窗口后Linner对象距离鼠标距离30~130
this.far = Math.random()*100+30;
// 画线条
this.draw = function(onPosition){
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.lineWidth = this.lineW;
ctx.moveTo(onPosition.x,onPosition.y);
ctx.lineTo(this.x,this.y);
ctx.stroke();
}
// 线条位置的更新
this.update = function(){
var ls = {
x : this.x,
y : this.y
}
this.x = mouse.x + Math.cos(this.theta)*this.far;
this.y = mouse.y + Math.sin(this.theta)*this.far;
this.theta += this.speet;
this.draw(ls);
}
}
// 动画
function anima(){
// 拖尾效果用一层带透明度的白色矩阵对上一次画的图进行覆盖
ctx.fillStyle = 'rgba(255,255,255,0.1)';
ctx.fillRect(0,0,canvas.width,canvas.height);
// 对每一个Linner对象进行位置更新
for(var i =0;i<a.length;i++){
a[i].update();
}
requestAnimationFrame(anima);
}
// 窗口文档显示区宽高
canvas.width = innerWidth;
canvas.height = innerHeight;
var a =[];
// 设置150个Linner对象
for(var i =0;i<100;i++){
a.push(new Linner(canvas.width/2,canvas.height/2,gc(),5,0.02));
}
anima();
</script>
</body>
</html>