分享以下效果
復制下一代到你的項目即可
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Particle 粒子特效</title><style>* {margin: 0;padding: 0;overflow: hidden;}html, body {width: 100%;height: 100%;background-color: #292d35;}</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>window.onload = function() {ParticleEffect.run();// test();};// 實時獲取窗口大小 和 從緩存中獲取窗口大小 的性能對比function test() {var cache = {width: 1024, height: 780};function test(executeFunc, times) {var start, end, num = times;start = new Date();while(times--) {executeFunc();}end = new Date();console.log(executeFunc.name + ' executes ' + num + 'times and takes ' + (end.getTime() - start.getTime()) / 1000 + 's.');}function getWindowSizeRealTime() {return {width: window.innerWidth || document.documentElement.clientWidth,height: window.innerHeight || document.documentElement.clientHeight};}function getWindowSizeFromCache() {return cache;}[1000, 10000, 100000, 1000000].forEach(function(times) {test(getWindowSizeRealTime, times);test(getWindowSizeFromCache, times);});}// 粒子特效var ParticleEffect = {ctx: null,canvas: null,particles: [],mouseCoordinates: {x: 0, y: 0},config: {id: 'canvas', //count: 150, // 默認創建粒子數量radius: 1, // 默認粒子半徑vxRange: [-1, 1], // 默認粒子橫向移動速度范圍vyRange: [-1, 1], // 默認粒子縱向移動速度范圍scaleRange: [.5, 1], // 默認粒子縮放比例范圍lineLenThreshold: 125, // 默認連線長度閾值color: 'rgba(255,255,255,.2)' // 默認粒子、線條的顏色},init: function(newConfig) {// 更新config配置newConfig && Object.keys(newConfig).forEach(function(key) {_this.config[key] = newConfig[key];});var _this = this;this.canvas = document.getElementById(this.config.id);this.ctx = this.canvas.getContext('2d');// 只有在瀏覽器支持canvas的情況下才有效if(this.ctx) {Utils.updateWindowSize();var windowSize = Utils.getWindowSize();// 設置canvas寬高this.canvas.width = windowSize.width;this.canvas.height = windowSize.height;// 生成粒子var times = this.config.count;this.particles = [];while(times--) {this.particles.push(new Particle({x: Utils.rangeRandom(this.config.radius, windowSize.width - this.config.radius),y: Utils.rangeRandom(this.config.radius, windowSize.height - this.config.radius),vx: Utils.rangeRandom(this.config.vxRange[0], this.config.vxRange[1]),vy: Utils.rangeRandom(this.config.vyRange[0], this.config.vyRange[1]),color: this.config.color,scale: Utils.rangeRandom(this.config.scaleRange[0], this.config.scaleRange[1]),radius: this.config.radius}));}// 監聽鼠標的mouseMove事件,記錄下鼠標的x,y坐標window.addEventListener('mousemove', this.handleMouseMove.bind(this), false);// 監聽窗口大小改變事件window.addEventListener('resize', this.handleWindowResize.bind(this), false);// 兼容requestAnimationFrameUtils.supportRequestAnimationFrame();window.requestAnimationFrame(this.draw.bind(this));}},move: function() {var windowSize = Utils.getWindowSize();this.particles.forEach(function(item) {// 更新粒子坐標item.x += item.vx;item.y += item.vy;// 如果粒子碰到了左墻壁或右墻壁,則改變粒子的橫向運動方向if((item.x - item.radius < 0) || (item.x + item.radius > windowSize.width)) {item.vx *= -1;}// 如果粒子碰到了上墻壁或下墻壁,則改變粒子的縱向運動方向if((item.y - item.radius < 0) || (item.y + item.radius > windowSize.height)) {item.vy *= -1;}});},draw: function() {var _this = this;var lineLenThreshold = this.config.lineLenThreshold;var windowSize = Utils.getWindowSize();// 每次重新繪制之前,需要先清空畫布,把上一次的內容清空this.ctx.clearRect(0, 0, windowSize.width, windowSize.height);// 繪制粒子this.particles.forEach(function(item) {item.draw(_this.ctx);});// 繪制粒子之間的連線for(var i = 0; i < this.particles.length; i++) {for(var j = i + 1; j < this.particles.length; j++) {var distance = Math.sqrt(Math.pow(this.particles[i].x - this.particles[j].x, 2) + Math.pow(this.particles[i].y - this.particles[j].y, 2));if(distance < lineLenThreshold) {// 這里我們讓距離遠的線透明度淡一點,距離近的線透明度深一點this.ctx.strokeStyle = this.translateColors(this.config.color, (1 - distance / lineLenThreshold));this.ctx.beginPath();this.ctx.moveTo(this.particles[i].x, this.particles[i].y);this.ctx.lineTo(this.particles[j].x, this.particles[j].y);this.ctx.closePath();this.ctx.stroke();}}}// 繪制粒子和鼠標之間的連線for(i = 0; i < this.particles.length; i++) {distance = Math.sqrt(Math.pow(this.particles[i].x - this.mouseCoordinates.x, 2) + Math.pow(this.particles[i].y - this.mouseCoordinates.y, 2));if(distance < lineLenThreshold) {this.ctx.strokeStyle = this.translateColors(this.config.color, (1 - distance / lineLenThreshold));this.ctx.beginPath();this.ctx.moveTo(this.particles[i].x, this.particles[i].y);this.ctx.lineTo(this.mouseCoordinates.x, this.mouseCoordinates.y);this.ctx.closePath();this.ctx.stroke();}}// 粒子移動,更新相應的x, y坐標this.move();// 循環調用draw方法window.requestAnimationFrame(this.draw.bind(this));},handleMouseMove: function(event) {var x, y;event = event || window.event;if(event.pageX || event.pageY) {x = event.pageX;y = event.pageY;} else {x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;}this.mouseCoordinates = {x: x, y: y};},handleWindowResize: function() {Utils.updateWindowSize();var windowSize = Utils.getWindowSize();this.canvas.width = windowSize.width;this.canvas.height = windowSize.height;},translateColors: function(colorStr, ratio) {var r, g, b, a = 1, colorValues;if(colorStr[0] === '#') { // 傳的是#RRGGBB形式r = parseInt(colorStr.slice(1, 3), 16);g = parseInt(colorStr.slice(3, 5), 16);b = parseInt(colorStr.slice(5, 7), 16);} else if(colorStr.startsWith('rgb(')) { // 傳的是rgb(r,g,b)形式colorStr = colorStr.slice(4, colorStr.length - 1);colorValues = colorStr.split(',');r = parseInt(colorValues[0].trim());g = parseInt(colorValues[1].trim());b = parseInt(colorValues[2].trim());} else if(colorStr.startsWith('rgba(')) { // 傳的是rgba(r,g,b,a)形式colorStr = colorStr.slice(5, colorStr.length - 1);colorValues = colorStr.split(',');r = parseInt(colorValues[0].trim());g = parseInt(colorValues[1].trim());b = parseInt(colorValues[2].trim());a = parseFloat(colorValues[3].trim());}return 'rgba(' + r + ',' + g + ',' + b + ',' + a * ratio + ')';},run: function(config) {this.init(config);}};/*** Particle 粒子類*/function Particle(attr) {// 粒子屬性this.x = attr.x; // 粒子在畫布中的橫坐標this.y = attr.y; // 粒子在畫布中的縱坐標this.vx = attr.vx; // 粒子的橫向運動速度this.vy = attr.vy; // 粒子的縱向運動速度this.color = attr.color; // 粒子的顏色this.scale = attr.scale; // 粒子的縮放比例this.radius = attr.radius; // 粒子的半徑大小// 繪制方法if(typeof Particle.prototype.draw === 'undefined') {Particle.prototype.draw = function(ctx) {// canvas畫圓方法ctx.beginPath();ctx.fillStyle = this.color;ctx.strokeStyle = this.color;ctx.arc(this.x, this.y, this.radius * this.scale, 0, 2 * Math.PI, false);ctx.closePath();ctx.fill();}}}// 工具var Utils = {_windowSize: {width: 0,height: 0},getWindowSize: function() {return this._windowSize;},updateWindowSize: function() {this._windowSize.width = this.getWindowWidth();this._windowSize.height = this.getWindowHeight();},getWindowWidth: function() {return window.innerWidth || document.documentElement.clientWidth;},getWindowHeight: function() {return window.innerHeight || document.documentElement.clientHeight;},rangeRandom: function(min, max) {const diff = max - min;return min + Math.random() * diff;},supportRequestAnimationFrame: function() {if(!window.requestAnimationFrame) {window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||window.mozRequestAnimationFrame ||window.oRequestAnimationFrame ||window.msRequestAnimationFrame ||function (callback) {setInterval(callback, 1000 / 60)});}}};
</script>
</body>
</html>
總結
以上是生活随笔為你收集整理的canvas动画粒子效果分享,可以做背景,超级好看的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。