今天我來分享一段非常有趣的HTML代碼,它可以讓頁面出現(xiàn)炫酷的煙花效果!這個效果可以用來裝飾您的網(wǎng)站或者為特別的場合制作一個獨(dú)一無二的頁面。
下面就是代碼:
<canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var mouse = { x: undefined, y: undefined }; var maxRadius = 40; var minRadius = 5; var colorArray = [ '#2C3E50', '#E74C3C', '#ECF0F1', '#3498DB', '#2980B9' ]; window.addEventListener('mousemove', function(event){ mouse.x = event.x; mouse.y = event.y; }); window.addEventListener('resize', function(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; init(); }); function Circle(x, y, radius, dx, dy){ this.x = x; this.y = y; this.radius = radius; this.dx = dx; this.dy = dy; this.color = colorArray[Math.floor(Math.random() * colorArray.length)]; this.draw = function(){ ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); ctx.fillStyle = this.color; ctx.fill(); }; this.update = function(){ if(this.x + this.radius >innerWidth || this.x - this.radius< 0) { this.dx = -this.dx; } if(this.y + this.radius >innerHeight || this.y - this.radius< 0) { this.dy = -this.dy; } this.x += this.dx; this.y += this.dy; //interactivity if(mouse.x - this.x< 50 && mouse.x - this.x >-50 && mouse.y - this.y< 50 && mouse.y - this.y >-50){ if(this.radius< maxRadius){ this.radius += 1; } } else if(this.radius >minRadius){ this.radius -= 1; } this.draw(); }; } var circleArray = []; function init(){ circleArray = []; for(var i = 0; i< 500; i++) { var radius = Math.random() * 3 + 1; var x = Math.random() * (innerWidth - radius * 2) + radius; var y = Math.random() * (innerHeight - radius * 2) + radius; var dx = (Math.random() - 0.5) * 2; var dy = (Math.random() - 0.5) * 2; circleArray.push(new Circle(x, y, radius, dx, dy)); } } function animate(){ requestAnimationFrame(animate); ctx.clearRect(0, 0, innerWidth, innerHeight); for(var i = 0; i< circleArray.length; i++) { circleArray[i].update(); } } init(); animate(); </script>
可以看到,這段代碼主要使用了HTML5的canvas標(biāo)簽和JavaScript的動畫函數(shù)requestAnimationFrame。通過定義一個Circle類來描述每一個煙花,維護(hù)煙花的位置、半徑、速度和顏色等屬性,并在每一幀動畫中更新和繪制這些煙花。同時,它還通過監(jiān)聽鼠標(biāo)移動事件和窗口大小改變事件來實(shí)現(xiàn)交互效果,讓煙花能夠隨著鼠標(biāo)的移動而變大或變小。
所以如果您想要在頁面上加入炫酷的煙花效果,就可以嘗試使用這段代碼了。希望這篇文章對您有所幫助,謝謝閱讀!