<!DOCTYPE html>
<html>
<head>
	<title>粒子生长树</title>
	<meta charset="utf-8">
	<style>
		canvas{
			background-color: black;
			display: block;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<canvas id="canvas"></canvas>
<pre><code>&lt;script&gt;
	// 创建画布
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');

	// 设置画布宽高
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;

	// 创建粒子类
	function Particle(x, y, radius, color){
		this.x = x || Math.random() * canvas.width;
		this.y = y || Math.random() * canvas.height;
		this.radius = radius || Math.random() * 3;
		this.color = color || '#fff';
		this.speed = {
			x: Math.random() * 2 - 1,
			y: Math.random() * 2 - 1
		};

		// 绘制粒子
		this.draw = function(){
			ctx.beginPath();
			ctx.fillStyle = this.color;
			ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
			ctx.fill();
		};

		// 更新粒子位置
		this.update = function(){
			this.x += this.speed.x;
			this.y += this.speed.y;

			if(this.x &lt; 0 || this.x &gt; canvas.width){
				this.speed.x = -this.speed.x;
			}

			if(this.y &lt; 0 || this.y &gt; canvas.height){
				this.speed.y = -this.speed.y;
			}
		};
	}

	// 创建粒子数组
	var particles = [];

	// 创建树枝数组
	var branches = [];

	// 添加粒子
	function addParticle(){
		particles.push(new Particle());
	}

	// 添加树枝
	function addBranch(){
		var particleA = particles[Math.floor(Math.random() * particles.length)];
		var particleB = particles[Math.floor(Math.random() * particles.length)];
		branches.push({
			pointA: {x: particleA.x, y: particleA.y},
			pointB: {x: particleB.x, y: particleB.y},
			color: '#fff'
		});
	}

	// 绘制树枝
	function drawBranch(branch){
		ctx.beginPath();
		ctx.strokeStyle = branch.color;
		ctx.moveTo(branch.pointA.x, branch.pointA.y);
		ctx.lineTo(branch.pointB.x, branch.pointB.y);
		ctx.stroke();
	}

	// 更新画布
	function update(){
		// 清空画布
		ctx.clearRect(0, 0, canvas.width, canvas.height);

		// 更新粒子位置
		for(var i = 0; i &lt; particles.length; i++){
			particles[i].update();
		}

		// 绘制粒子
		for(var i = 0; i &lt; particles.length; i++){
			particles[i].draw();
		}

		// 添加树枝
		if(particles.length &gt; 1 &amp;&amp; branches.length &lt; particles.length - 1){
			addBranch();
		}

		// 绘制树枝
		for(var i = 0; i &lt; branches.length; i++){
			drawBranch(branches[i]);
		}
	}

	// 循环更新画布
	setInterval(update, 1000/60);

	// 添加粒子
	for(var i = 0; i &lt; 50; i++){
		addParticle();
	}
&lt;/script&gt;
</code></pre>
</body>
</html>
粒子生长树 HTML 代码示例 - 互动式视觉效果

原文地址: https://www.cveoy.top/t/topic/op64 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录