以下是一个使用HTML5 Canvas制作的告白情人节爱心动画的示例代码:
<!DOCTYPE html>
<html>
<head>�
<title>告白情人节爱心动画</title>
<style>
canvas {
background-color: #222;
}
</style>
</head>
<body>
<canvas id="heartCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('heartCanvas');
const ctx = canvas.getContext('2d');
const heart = new Heart(ctx, 200, 200, 100, 100, 5);
// 动画循环
(function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
heart.update();
window.requestAnimationFrame(animate);
})();
// 告白话语动画
const text = new LoveText(ctx, "I Love You!", 200, 100, 20, "#ff0000");
(function animateText() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
text.update();
window.requestAnimationFrame(animateText);
})();
// 告白话语类
class LoveText {
constructor(ctx, text, x, y, speed, color) {
this.ctx = ctx;
this.text = text;
this.x = x;
this.y = y;
this.speed = speed;
this.color = color;
this.opacity = 0;
}
update() {
this.opacity += this.speed / 255;
this.ctx.globalAlpha = this.opacity / 255;
this.ctx.fillStyle = this.color;
this.ctx.font = "40px Arial";
this.ctx.textAlign = "center";
this.ctx.fillText(this.text, this.x, this.y);
if (this.opacity >= 255) {
this.opacity = 255;
}
}
}
// 心形类
class Heart {
constructor(ctx, x, y, width, height, speed) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
this.scale = 1;
this.rotation = 0;
}
update() {
this.rotatio