本代码可制作一个全屏漂浮的粒子,点击可停下,再次点击移动 效果图:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>粒子</title> <style> * { margin: 0; padding: 0; overflow: hidden; } </style> <script> //随机数获取 function random(min, max) { return Math.random() * (max - min) + min; } //获取窗口宽高 var width = window.innerWidth; var height = window.innerHeight; var colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1' ]; function Bubblue() { this.r = random(2, 5); this.x = random(this.r, width - this.r); this.y = random(this.r, height - this.r); this.color = colors[Math.floor(random(0, colors.length))]; //偏移步长 this.xr = random(-5, 5); this.yr = random(-5, 5); } Bubblue.prototype = { //绘制 draw: function(context) { context.beginPath(); context.arc(this.x, this.y, this.r, 0, Math.PI * 2); context.fillStyle = this.color; context.fill(); }, //移动 move: function(context) { this.x += this.xr; this.y += this.yr; //边缘检测 (this.x + this.r > width || this.x - this.r < 0) ? this.xr = -this.xr: null; (this.y + this.r > height || this.y - this.r < 0) ? this.yr = -this.yr: null; this.draw(context); } }; window.onload = function() { //设置宽高 var canvas = document.querySelector('canvas'); canvas.width = width; canvas.height = height; var context = canvas.getContext('2d'); //数组存储 var arr = []; var total = []; for (var i = 0; i < 1000; i++) { var bubblue = new Bubblue(); bubblue.draw(context); arr.push(bubblue); } var id = setInterval(function() { context.clearRect(0, 0, width, height); //移动 for (var i = 0; i < arr.length; i++) { arr[i].move(context); } }, 1000 / 60); var count = 0; canvas.onclick = function() { if (count++ % 2 == 0) { //停止 clearInterval(id); } else { //运行 id = setInterval(function() { context.clearRect(0, 0, width, height); //移动 for (var i = 0; i < arr.length; i++) { arr[i].move(context); } }, 1000 / 60); } } } </script> </head> <body> <canvas title="点击停止,再次点击活动"></canvas> </body> </html>