动态爱心html代码
时间: 2023-11-16 18:59:10 浏览: 113
动态爱心HTML代码是一种使用HTML5 Canvas和JavaScript创建的动态效果,可以在网页上显示一个跳动的爱心。通常,这种效果是通过在Canvas上绘制多个粒子来实现的,每个粒子都有自己的位置、速度和大小。这些粒子会在Canvas上移动,并在一定时间内消失。通过控制粒子的数量、速度、大小和持续时间等参数,可以创建出不同的动态爱心效果。
下面是一个简单的动态爱心HTML代码的例子:
```
<!DOCTYPE html>
<html>
<head>
<title>动态爱心</title>
<style>
html, body {
height: 100%;
padding: 0;
margin: 0;
background: #000;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="heart"></canvas>
<script>
var canvas = document.getElementById('heart');
var ctx = canvas.getContext('2d');
var particles = [];
var settings = {
particles: {
length: 500,
duration: 2,
velocity: 100,
effect: -0.75,
size: 30,
},
};
function Particle(x, y, vx, vy, size, duration) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.size = size;
this.duration = duration;
this.alpha = 1;
}
Particle.prototype.update = function(dt) {
this.x += this.vx * dt;
this.y += this.vy * dt;
this.alpha = Math.max(0, this.alpha - dt / this.duration);
};
Particle.prototype.draw = function(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = '#ff69b4';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
};
function createParticles() {
for (var i = 0; i < settings.particles.length; i++) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var angle = Math.random() * 2 * Math.PI;
var speed = settings.particles.velocity * (0.5 + Math.random() / 2);
var vx = speed * Math.cos(angle);
var vy = speed * Math.sin(angle);
var size = settings.particles.size * (0.5 + Math.random() / 2);
var duration = settings.particles.duration * (0.5 + Math.random() / 2);
particles.push(new Particle(x, y, vx, vy, size, duration));
}
}
function updateParticles(dt) {
for (var i = 0; i < particles.length; i++) {
particles[i].update(dt);
if (particles[i].alpha <= 0) {
particles.splice(i, 1);
i--;
}
}
}
function drawParticles(ctx) {
for (var i = 0; i < particles.length; i++) {
particles[i].draw(ctx);
}
}
function loop() {
var now = new Date().getTime();
var dt = (now - lastTime) / 1000;
lastTime = now;
ctx.clearRect(0, 0, canvas.width, canvas.height);
updateParticles(dt);
drawParticles(ctx);
if (particles.length < settings.particles.length) {
createParticles();
}
requestAnimationFrame(loop);
}
var lastTime = new Date().getTime();
createParticles();
loop();
</script>
</body>
</html>
```
阅读全文