今天我們來學習一下如何制作HTML炫彩粒子效果!首先,我們需要在HTML文件中引入一個canvas標簽:
<canvas id="myCanvas"></canvas>
接著,我們需要使用JavaScript來控制canvas繪制粒子。下面是一段實現動態粒子效果的JavaScript代碼:
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var particles = []; function Particle(x, y) { this.x = x; this.y = y; this.vx = Math.random() * 10 - 5; this.vy = Math.random() * 10 - 5; this.color = "#" + Math.floor(Math.random() * 16777215).toString(16); this.size = Math.random() * 10 + 5; } Particle.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fillStyle = this.color; ctx.fill(); } function update() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(function(particle) { particle.x += particle.vx; particle.y += particle.vy; if (particle.x >canvas.width || particle.x< 0) { particle.vx *= -1; } if (particle.y >canvas.height || particle.y< 0) { particle.vy *= -1; } particle.draw(); }); requestAnimationFrame(update); } for (var i = 0; i< 50; i++) { var particle = new Particle(Math.random() * canvas.width, Math.random() * canvas.height); particles.push(particle); } update();
代碼注釋如下:
// 獲取canvas和繪圖上下文 var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); // 粒子對象 function Particle(x, y) { // 粒子位置及速度 this.x = x; this.y = y; this.vx = Math.random() * 10 - 5; this.vy = Math.random() * 10 - 5; // 粒子顏色及大小 this.color = "#" + Math.floor(Math.random() * 16777215).toString(16); this.size = Math.random() * 10 + 5; } // 繪制粒子 Particle.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fillStyle = this.color; ctx.fill(); } // 粒子動畫更新 function update() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(function(particle) { particle.x += particle.vx; particle.y += particle.vy; if (particle.x >canvas.width || particle.x< 0) { particle.vx *= -1; } if (particle.y >canvas.height || particle.y< 0) { particle.vy *= -1; } particle.draw(); }); requestAnimationFrame(update); } // 初始化粒子 var particles = []; for (var i = 0; i< 50; i++) { var particle = new Particle(Math.random() * canvas.width, Math.random() * canvas.height); particles.push(particle); } // 開始動畫 update();
完成以上步驟后,我們就可以看到一個炫彩的粒子效果啦!