HTML代碼可以創建出各種不同的效果,其中滿屏愛心代碼是一種非常有趣的代碼,在網頁上展示出一屏幕滿滿的紅色愛心。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>滿屏愛心</title> </head> <body> <div style="position: absolute;left: 0;top: 0;width: 100%;height: 100%;overflow: hidden;"> <span style="color: red;font-size: 20px;"> <!-- 心形字符 --> ♥ <!-- 心形字符 --> </span> </div> <script> // 粒子數量 var particleCount = 50; // 粒子尺寸 var particleSize = 20; // 最大速度 var maxSpeed = 3; // 最大距離 var maxDistance = 100; var canvas = document.createElement('canvas'); document.body.appendChild(canvas); function Particle(startX, startY, size) { this.x = startX; this.y = startY; this.size = size; this.speedX = (Math.random() - 0.5) * maxSpeed; this.speedY = (Math.random() - 0.5) * maxSpeed; } Particle.prototype.move = function() { this.x += this.speedX; this.y += this.speedY; } function getRandomOffset() { return (Math.random() - 0.5) * maxDistance; } function getRandomSize() { return particleSize + (Math.random() - 0.5) * 10; } var particles = []; for (var i = 0; i< particleCount; i++) { particles.push(new Particle(0, 0, getRandomSize())); } function draw() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; var center_x = canvas.width / 2; var center_y = canvas.height / 2; for (var i = 0; i< particles.length; i++) { var particle = particles[i]; var particle_x = center_x + particle.x + getRandomOffset(); var particle_y = center_y + particle.y + getRandomOffset(); canvas.getContext('2d').fillRect(particle_x, particle_y, particle.size, particle.size); } } setInterval(function() { canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i< particles.length; i++) { particles[i].move(); } draw(); }, 30); </script> </body> </html>
這段代碼中,基本的滿屏愛心效果是通過HTML中的字符實現的,通過定位讓其鋪滿整個屏幕。在JavaScript中,定義了粒子的數量、大小、速度以及最大距離,通過創建粒子實例來隨機生成這些屬性。在每一次重繪畫布時,進行粒子的移動、修改顏色、大小等屬性,并利用canvas畫布進行實現。
下一篇java t 和 e