最近我學(xué)習(xí)了一些有關(guān)HTML特效的知識,其中讓我印象深刻的是銀河系代碼。這是一個(gè)非常酷的效果,會(huì)在你的網(wǎng)站上呈現(xiàn)出流星穿梭和星空閃爍的畫面。接下來,讓我們來看一下這個(gè)特效的代碼吧:
<canvas id="galaxy"></canvas> <script> var canvas = document.getElementById("galaxy"); var ctx = canvas.getContext("2d"); var stars = 1000; // 創(chuàng)建流星 var meteors = []; function Meteor() { this.x = Math.random() * canvas.width; this.y = 0; this.length = Math.random() * 80 + 10; this.speed = Math.random() * 6 + 2; this.angle = Math.random() * 60 + 40; } Meteor.prototype.draw = function() { ctx.beginPath(); ctx.moveTo(this.x, this.y); var x2 = this.x + this.length * Math.cos(this.angle * Math.PI / 180); var y2 = this.y + this.length * Math.sin(this.angle * Math.PI / 180); ctx.lineTo(x2, y2); ctx.strokeStyle = "#fff"; ctx.stroke(); } Meteor.prototype.update = function() { this.x += this.speed * Math.cos(this.angle * Math.PI / 180); this.y += this.speed * Math.sin(this.angle * Math.PI / 180); if (this.y >canvas.height) { this.x = Math.random() * canvas.width; this.y = 0; } } Meteor.prototype.animate = function() { this.update(); this.draw(); } for (var i = 0; i< Math.round(stars / 10); i++) { meteors.push(new Meteor()); } // 創(chuàng)建星星 function Star() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.radius = Math.random() * 1.5; } Star.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = "rgba(255, 255, 255, " + Math.random() + ")"; ctx.fill(); } for (var i = 0; i< stars; i++) { new Star().draw(); } // 動(dòng)畫 function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i< meteors.length; i++) { meteors[i].animate(); } requestAnimationFrame(animate); } animate(); </script>
以上代碼是一個(gè)使用Canvas繪制的銀河特效,其中包含了創(chuàng)建流星和星星的方法,同時(shí)也包含了動(dòng)畫的實(shí)現(xiàn)方式,讓這個(gè)特效更加生動(dòng)逼真。如果你想要在自己的網(wǎng)站上使用銀河系特效,只需要將以上代碼復(fù)制粘貼到你的HTML文件中即可。