3D粒子爱心代码HTML
时间: 2024-05-11 11:13:10 浏览: 283
3D爱心,html文件
3D粒子爱心代码的HTML实现方式有很多种,其中比较常用的是使用HTML5中的canvas元素和JavaScript来实现。
以下是一个简单的例子:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>3D粒子爱心</title>
<style>
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
var particles = [];
var particleCount = 200;
var heart = {
x: 0,
y: 0,
size: 150,
angle: 0
};
var colors = ['#ff0000', '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4caf50', '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107'];
function Particle() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = Math.random() * 4 - 2;
this.vy = Math.random() * 4 - 2;
this.size = Math.random() * 2 + 1;
this.color = colors[Math.floor(Math.random() * colors.length)];
}
function createParticles() {
for (var i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
}
function updateParticles() {
for (var i = 0; i < particles.length; i++) {
particles[i].x += particles[i].vx;
particles[i].y += particles[i].vy;
if (particles[i].x < -50) {
particles[i].x = canvas.width + 50;
}
if (particles[i].y < -50) {
particles[i].y = canvas.height + 50;
}
if (particles[i].x > canvas.width + 50) {
particles[i].x = -50;
}
if (particles[i].y > canvas.height + 50) {
particles[i].y = -50;
}
}
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'lighter';
for (var i = 0; i < particles.length; i++) {
ctx.fillStyle = particles[i].color;
ctx.beginPath();
ctx.arc(particles[i].x, particles[i].y, particles[i].size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
}
function drawHeart() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#ffffff';
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(heart.angle);
ctx.scale(heart.size / 100, heart.size / 100);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(0, -60, -80, -100, -130, -60);
ctx.bezierCurveTo(-180, -20, -180, 50, -130, 90);
ctx.bezierCurveTo(-100, 110, -60, 140, 0, 170);
ctx.bezierCurveTo(60, 140, 100, 110, 130, 90);
ctx.bezierCurveTo(180, 50, 180, -20, 130, -60);
ctx.bezierCurveTo(80, -100, 0, -60, 0, 0);
ctx.closePath();
ctx.fill();
}
function loop() {
requestAnimationFrame(loop);
updateParticles();
drawParticles();
heart.angle += Math.PI / 180 * 2;
if (heart.size < 300) {
heart.size += 1;
}
drawHeart();
}
createParticles();
loop();
</script>
</body>
</html>
```
在这个例子中,我们创建了一个canvas元素,并通过JavaScript来生成粒子和绘制爱心。具体来说,我们首先定义了一个Particle类,表示一个粒子的基本属性,然后通过createParticles函数生成了一定数量的随机粒子。在loop函数中,我们通过updateParticles函数更新所有粒子的位置,然后在drawParticles函数中绘制所有粒子。此外,我们还定义了一个heart对象来表示爱心的属性和状态,并在drawHeart函数中绘制爱心。最后,在loop函数中不断更新爱心的状态和大小,实现了一个动态的3D粒子爱心效果。
阅读全文