用html写一个动态生长粒子树代码
时间: 2023-06-10 11:05:48 浏览: 184
当然,我可以为您提供一个基本的动态生长粒子树代码。以下是示例代码:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Particle Tree</title>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
background: #000;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="tree.js"></script>
</body>
</html>
```
JavaScript代码(tree.js):
```javascript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;
ctx.translate(width / 2, height / 2);
let particles = [];
function Particle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
}
Particle.prototype.update = function() {
this.radius -= 0.02; // 控制粒子大小
}
function createParticles(x, y, count) {
while (count--) {
let angle = Math.random() * 360;
let radius = Math.random() * 20 + 1;
let particle = new Particle(x, y, radius);
particle.vx = Math.cos(angle) * radius * 0.1; // 控制粒子运动速度
particle.vy = Math.sin(angle) * radius * 0.1; // 控制粒子运动速度
particles.push(particle);
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(-width / 2, -height / 2, width, height);
if (particles.length < 200) {
createParticles(0, 0, 1);
}
for (let i = 0; i < particles.length; i++) {
let particle = particles[i];
if (particle.radius > 0) {
particle.draw();
particle.update();
particle.x += particle.vx;
particle.y += particle.vy;
} else {
particles.splice(i, 1);
}
}
}
animate();
```
这份代码是使用 Canvas 绘制粒子树的样式,每次随机产生一定数量的粒子,控制它们运动的速度以及大小,形成一个不停生长的粒子树效果。