今天我們來練習使用HTML來畫動態星空,讓網頁變得更加生動有趣。
<!DOCTYPE html> <html> <head> <title>動態星空</title> <script> window.addEventListener('load', function() { var canvas = document.getElementById('stars'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var stars = []; var numStars = 200; var createStar = function() { var star = { x: Math.random() * canvas.width, y: Math.random() * canvas.height, radius: Math.random(), vx: Math.floor(Math.random() * 20) - 10, vy: Math.floor(Math.random() * 20) - 10 }; stars.push(star); } for(var i = 0; i < numStars; i++) { createStar(); } var drawStar = function() { for(var i = 0; i < numStars; i++) { var star = stars[i]; ctx.beginPath(); ctx.arc(star.x, star.y, star.radius, 0, 2 * Math.PI); ctx.fillStyle = '#FFF'; ctx.fill(); star.x += star.vx / 30; star.y += star.vy / 30; if(star.x < -50) star.x = canvas.width + 50; if(star.y < -50) star.y = canvas.height + 50; if(star.x > canvas.width + 50) star.x = -50; if(star.y > canvas.height + 50) star.y = -50; } } var animate = function() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawStar(); requestAnimationFrame(animate); } animate(); }, false); </script> </head> <body> <canvas id="stars"></canvas> </body> </html>
代碼中,我們使用了canvas標簽來獲取一個二維上下文,并且設置了畫布大小和星星的數量。接著,我們循環繪制每顆星星,并且設置了它的位置,大小和速度,并且定義了函數做動畫。動畫函數中,我們不斷清除畫布和重新繪制星星。最后,我們在網頁中使用了canvas標簽來展示我們的動態星空。