HTML5代碼之粒子特效系列是一種基于HTML5技術實現的動態效果。它通過將諸如文本、圖像等元素劃分為一個個小粒子,讓它們在頁面中呈現出粒子運動的效果。下面是一些常見的粒子特效:
// 點陣動畫:生成一些隨機的小圓點 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var particles = []; var particleCount = 200; for (var i = 0; i< particleCount; i++) { particles.push(new particle()); } function particle() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = Math.random() * 4 - 2; this.vy = Math.random() * 4 - 2; this.radius = Math.random() * 2; } function draw() { for (var i = 0; i< particles.length; i++) { var p = particles[i]; ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, false); ctx.fillStyle = 'white'; ctx.fill(); p.x += p.vx; p.y += p.vy; if (p.x< -50) p.x = canvas.width + 50; if (p.y< -50) p.y = canvas.height + 50; if (p.x >canvas.width + 50) p.x = -50; if (p.y >canvas.height + 50) p.y = -50; } } setInterval(draw, 30);
上述代碼使用了HTML5中的Canvas標簽,通過向畫布上添加小圓點來實現點陣動畫特效。
//火焰效果:通過逆向工程來解析像素 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = "fire.jpg"; img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); var pixels = ctx.getImageData(0, 0, img.width, img.height).data; for (var i = 0; i< pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var gray = (r + g + b) / 3; pixels[i] = gray + 50; pixels[i + 1] = gray + 50; pixels[i + 2] = gray + 50; } ctx.putImageData(ctx.getImageData(0, 0, img.width, img.height), 0, 0); }
上述代碼利用HTML5的Canvas和getImageData()函數逆向工程了一個圖片,然后對其像素進行了重新著色,最后形成了類似于火焰的效果。這一示例展示了HTML5特效的高度可定制性。