粒子生长树 HTML 代码示例 - 互动式视觉效果
<!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><script>
// 创建画布
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 < 0 || this.x > canvas.width){
this.speed.x = -this.speed.x;
}
if(this.y < 0 || this.y > 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 < particles.length; i++){
particles[i].update();
}
// 绘制粒子
for(var i = 0; i < particles.length; i++){
particles[i].draw();
}
// 添加树枝
if(particles.length > 1 && branches.length < particles.length - 1){
addBranch();
}
// 绘制树枝
for(var i = 0; i < branches.length; i++){
drawBranch(branches[i]);
}
}
// 循环更新画布
setInterval(update, 1000/60);
// 添加粒子
for(var i = 0; i < 50; i++){
addParticle();
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/op64 著作权归作者所有。请勿转载和采集!