html代码
<canvas id="canvas">您的浏览器不支持canvas</canvas>
css代码
#canvas { background-color: cadetblue; display: block; overflow: hidden; }
javascript代码
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //画布大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight; //鼠标路径 var mouseX = canvas.width / 2; var mouseY = canvas.height / 2; //浏览器窗口改变 window.onresize = function(){ canvas.width = window.innerWidth canvas.height = window.innerHeight } //生成随机数 function randomNum(x, y) { return Math.floor(Math.random() * (y - x + 1) + x); } // 创建小球对象 function Ball() {} Ball.prototype = { // 初始化 init: function(){ this.r = randomNum(0.1, 3); // 小球半径 this.color = "#fff"; // 小球颜色 // 随机坐标轴 this.x = randomNum(this.r, canvas.width - this.r); this.y = randomNum(this.r, canvas.height - this.r); //随机速度 this.speedX = randomNum(1, 3) * (randomNum(0, 1) ? 1 : -1); this.speedY = randomNum(1, 3) * (randomNum(0, 1) ? 1 : -1); }, move: function(){ // 小球移动 this.x += this.speedX * 0.2; // x轴移动 this.y += this.speedY * 0.2; // y轴移动 // 左边界 if(this.x <= this.r) { this.x = this.r; // 反方向 this.speedX *= -1; } // 右边界 if(this.x >= canvas.width - this.r) { this.x = canvas.width - this.r this.speedX *= -1; } //上边界 if(this.y <= this.r) { this.y = this.r; this.speedY *= -1; } //下边界 if(this.y >= canvas.height - this.r) { this.y = canvas.height - this.r; this.speedY *= -1; } }, draw: function(){ // 绘制小球 ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); ctx.fillStyle = this.color; ctx.fill(); } } var balls = []; // 小球盒子 for(var i = 0; i < 0.0002 * canvas.width * canvas.height; i++) { ball = new Ball(); // 实例化对象 ball.init() // 初始化数据 balls.push(ball); } setInterval(function() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布 for(var i = 0; i < balls.length; i++) { balls[i].move(); // 小球移动 balls[i].draw(); // 更新小球位置 if(ball_to_mouse(balls[i]) < 130) { // 球体与鼠标距离-->画线 ctx.lineWidth = (130 - ball_to_mouse(balls[i])) * 1.5 / 130; ctx.beginPath(); ctx.moveTo(balls[i].x, balls[i].y); ctx.lineTo(mouseX, mouseY); ctx.strokeStyle = balls[i].color; ctx.stroke(); } } for(var i = 0; i < balls.length; i++) { for(var j = 0; j < balls.length; j++) { if(ball_to_ball(balls[i], balls[j]) < 80) { // 球体之间距离-->画线 ctx.lineWidth = (80 - ball_to_ball(balls[i], balls[j])) * 0.6 / 80; // 线体透明 ctx.globalAlpha = (130 - ball_to_ball(balls[i], balls[j])) * 1 / 80; ctx.beginPath(); ctx.moveTo(balls[i].x, balls[i].y); ctx.lineTo(balls[j].x, balls[j].y); ctx.strokeStyle = balls[i].color; ctx.stroke(); } } } // 当前画布透明度 ctx.globalAlpha = 1.0; }, 30); //鼠标移动 canvas.|| window.event; mouseX = e.offsetX; mouseY = e.offsetY; } //鼠标跟每个点之间的距离 function ball_to_mouse(obj) { var disX = Math.abs(mouseX - obj.x); var disY = Math.abs(mouseY - obj.y); return Math.sqrt(disX * disX + disY * disY); } //两点之间的距离 function ball_to_ball(obj1, obj2) { var disX = Math.abs(obj1.x - obj2.x); var disY = Math.abs(obj1.y - obj2.y); return Math.sqrt(disX * disX + disY * disY); }