html爱心烟花特效代码记事本
时间: 2024-12-16 18:13:07 浏览: 20
HTML爱心烟花特效是一种常见的Web页面动画效果,它可以在页面中呈现出爱心或烟花的动态效果,让页面更加生动有趣。下面是一个HTML爱心烟花特效代码记事本的实现步骤:
1. 创建一个空白的HTML文件,并在其中添加一个canvas元素,设置其宽度和高度,用于绘制动画效果。
2. 在JavaScript中编写动画效果的实现代码,包括绘制爱心或烟花、添加事件监听器等。
3. 在CSS中定义canvas元素的样式,包括宽度、高度、背景颜色等。
下面是一个简单的HTML爱心烟花特效代码实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>HTML爱心烟花特效</title>
<style type="text/css">
canvas {
width: 100%;
height: 100%;
background-color: black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext('2d');
var heart = {
x: canvas.width / 2,
y: canvas.height / 2,
size: 100,
color: 'red'
};
var hearts = [];
var particles = [];
function drawHeart() {
context.beginPath();
context.fillStyle = heart.color;
context.moveTo(heart.x, heart.y + heart.size / 4);
context.quadraticCurveTo(heart.x - heart.size, heart.y - heart.size, heart.x, heart.y - heart.size / 1.5);
context.quadraticCurveTo(heart.x + heart.size, heart.y - heart.size, heart.x, heart.y + heart.size / 4);
context.fill();
}
function drawParticle() {
context.beginPath();
context.fillStyle = 'white';
context.arc(this.x, this.y, this.size, 0, Math.PI * 2);
context.fill();
}
function createParticle(x, y) {
for (var i = 0; i < 30; i++) {
particles.push({
x: x,
y: y,
size: Math.random() * 4,
speedX: Math.random() * 6 - 3,
speedY: Math.random() * 6 - 3,
color: 'white'
});
}
}
function updateParticle(particle) {
particle.x += particle.speedX;
particle.y += particle.speedY;
particle.size -= 0.1;
if (particle.size <= 0) {
particles.splice(particles.indexOf(particle), 1);
}
}
function loop() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
updateParticle(particles[i]);
drawParticle.call(particles[i]);
}
for (var i = 0; i < hearts.length; i++) {
if (hearts[i].size <= 0) {
hearts.splice(i, 1);
continue;
}
hearts[i].size -= 0.5;
drawHeart.call(hearts[i]);
}
}
canvas.addEventListener('click', function(event) {
createParticle(event.clientX, event.clientY);
hearts.push({
x: event.clientX,
y: event.clientY,
size: 100,
color: 'red'
});
});
setInterval(loop, 30);
</script>
</body>
</html>
```
阅读全文