HTML是一種超文本標記語言,可以用于構建網頁。在HTML中,我們可以使用代碼來實現各種動態效果,比如生日動態代碼。
<!DOCTYPE html>
<html>
<head>
<title>生日快樂</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, 'pink');
gradient.addColorStop(1, 'purple');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
var fontSize = 60;
var font = 'Arial';
var text = 'Happy Birthday!';
var offsetX = canvas.width / 2 - (text.length * fontSize * 0.4);
var offsetY = canvas.height / 2 + fontSize * 0.4;
context.font = fontSize + 'px ' + font;
context.fillStyle = 'white';
context.fillText(text, offsetX, offsetY);
var particleNumber = 50;
var particles = [];
for (var i = 0; i < particleNumber; i++) {
particles.push(new Particle(canvas.width, canvas.height));
}
function Particle(x, y) {
this.x = Math.random() * x;
this.y = Math.random() * y;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.radius = Math.random() * 10 + 5;
this.color = 'white';
}
Particle.prototype.draw = function() {
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
context.fillStyle = this.color;
context.fill();
context.closePath();
}
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > canvas.width) {
this.vx = -this.vx;
}
if (this.y < 0 || this.y > canvas.height) {
this.vy = -this.vy;
}
}
function animate() {
requestAnimationFrame(animate);
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
}
}
animate();
</script>
</body>
</html>
這段代碼將創建一個HTML頁面,包含一個canvas元素和JavaScript代碼。canvas元素用于繪制背景和粒子,JavaScript代碼定義了Particle類來創建粒子,以及animate函數用于更新粒子的位置和繪制背景和文本。
這段代碼可以通過復制粘貼到HTML文件中,保存并打開文件來預覽生日動態效果。