html3d动态粒子圣诞树代码
时间: 2023-12-25 22:30:19 浏览: 441
以下是一个使用HTML5编写的3D动态粒子圣诞树的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>3D动态粒子圣诞树</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [];
function Particle(x, y, radius, color, speedX, speedY) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.speedX = speedX;
this.speedY = speedY;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
};
Particle.prototype.update = function() {
this.x += this.speedX;
this.y += this.speedY;
if (this.radius > 0.2) {
this.radius -= 0.1;
}
this.draw();
};
function createParticles() {
for (var i = 0; i < 100; i++) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = Math.random() * 3 + 1;
var color = "rgba(255, 255, 255, 0.5)";
var speedX = Math.random() * 3 - 1.5;
var speedY = Math.random() * 3 - 1.5;
particles.push(new Particle(x, y, radius, color, speedX, speedY));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
if (particles[i].radius <= 0.2) {
particles.splice(i, 1);
i--;
}
}
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
createParticles();
animate();
</script>
</body>
</html>
```
这段代码使用HTML5的canvas元素和JavaScript编写了一个简单的3D动态粒子圣诞树效果。它创建了一些粒子对象,每个粒子都有自己的位置、半径、颜色和速度。在动画循环中,粒子会根据其速度移动,并逐渐减小半径,直到消失。
你可以将以上代码复制到一个HTML文件中,并在浏览器中打开该文件,即可看到3D动态粒子圣诞树的效果。
阅读全文