HTML5云粒子代碼是一種可以創建流動、漂浮的云朵效果的代碼。該代碼利用了HTML5的canvas元素,并且可以通過簡單的修改來自定義云朵的形狀、大小、顏色等屬性。
<canvas id="canvas"></canvas> <script type="text/javascript"> var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var ctx = canvas.getContext("2d"); var particles = []; var particle_count = 100; for(var i = 0; i< particle_count; i++) { particles.push(new particle()); } function particle() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; var angle = Math.random() * 360; this.vx = Math.cos(angle) * 2; this.vy = Math.sin(angle) * 2; this.size = Math.random() * 5 + 2; this.color = "#ffffff"; } function update() { ctx.clearRect(0, 0, canvas.width, canvas.height); for(var i = 0; i< particles.length; i++) { particles[i].x += particles[i].vx; particles[i].y += particles[i].vy; if(particles[i].x >canvas.width || particles[i].x< 0) { particles[i].vx = -particles[i].vx; } if(particles[i].y >canvas.height || particles[i].y< 0) { particles[i].vy = -particles[i].vy; } ctx.beginPath(); ctx.fillStyle = particles[i].color; ctx.arc(particles[i].x, particles[i].y, particles[i].size, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); } } setInterval(update, 30); </script>
上述代碼中,canvas元素用于創建畫布,通過為其設置寬度和高度,我們可以實現畫布與窗口大小的自適應。particles數組中存儲了所有的云朵個體,可以通過更改particle_count的數量來增加或減少云朵的數量。particle()函數用于創建每個云朵的屬性,包括位置、速度、大小和顏色等。update()函數用于更新云朵的位置,并將其顯示在畫布上。